【问题标题】:cannot change observable from try catch block in mobx strict mode在 mobx 严格模式下无法从 try catch 块更改 observable
【发布时间】:2017-09-01 05:58:05
【问题描述】:
class Someclass {
  @observable waiting = false;
  @observable error = null;

  @action.bound
  async authenticate({login, password}) {
    try {
      this.waiting = true;
      const res = await myService.authenticate(login, password);
    } catch (error) {
      this.error = error; // Gives an error: Invariant Failed
    } finally {
      this.waiting = false; // Gives an error: Invariant Failed

      // I've tried doing this too
      // action(() => {
      //   this.waiting = false;
      // })
    }
  }


}

在上面的示例中,从 catch 和 finally 块中更改值会在严格模式下给出错误或警告 Invariant Failed。正确的做法是什么?

【问题讨论】:

    标签: mobx mobx-react


    【解决方案1】:

    async 函数内部,我们必须在runInAction 实用方法中包装一个函数,以便在strict 模式下改变@observable。示例。

    class Someclass {
      @observable waiting = false;
      @observable error = null;
    
      @action.bound
      async authenticate({login, password}) {
        try {
          this.waiting = true;
          const res = await myService.authenticate(login, password);
        } catch (error) {
          runInAction(() => {
            this.error = error;
          });
        } finally {
          runInAction(() => {
            this.waiting = false;
          });
        }
      }
    
    
    }
    

    View this related issue on github

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      相关资源
      最近更新 更多