无法在mobx严格模式下从try catch块更改observable

时间:2017-09-01 05:58:06

标签: mobx mobx-react

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块中的值会在严格模式下出现错误或警告不变失败。什么是正确的方法?

1 个答案:

答案 0 :(得分:1)

async函数内部,我们必须在runInAction实用程序方法中包含一个函数,以便在@observable模式下变更strict。实施例。

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