Using the MobX @action decorator with async functions and .then

后端 未结 3 714
一整个雨季
一整个雨季 2021-02-19 05:02

I\'m using MobX 2.2.2 to try to mutate state inside an async action. I have MobX\'s useStrict set to true.

@action someAsyncFunction(args) {
  fetch(`http://loca         


        
3条回答
  •  鱼传尺愫
    2021-02-19 05:15

    note that in async method you manualy have to start a new action/transaction after awaiting something:

    @mobx.action async someAsyncFunction(args) {
      this.loading = true;
    
      var result = await fetch(`http://localhost:8080/some_url`, {
        method: 'POST',
        body: {
          args
        }
      });
      var json = await result.json();
      @mobx.runInAction(()=> {
         this.someStateProperty = json
         this.loading = false;
      });
    }
    

    my preference

    I prefer to not use @mobx.action/runInAction directly but always place it on an private method. And let public methods call private methods that actually update the state:

    public someAsyncFunction(args) {
      this.startLoading();
      return fetch(`http://localhost:8080/some_url`, {
        method: 'POST',
        body: {
          args
        }
      })
      .then(res => res.json())
      .then(this.onFetchResult);
    }
    
    @mobx.action 
    private startLoading = () => {
       this.loading = true;
    }
    
    @mobx.action 
    private onFetchResult = (json) => {
       this.someStateProperty = json;
       this.loading = false;
    }
    

提交回复
热议问题