cannot change observable from try catch block in mobx strict mode

932 views Asked by At
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;
      // })
    }
  }


}

In above example altering values from catch and finally block gives an error or warning Invariant Failed with strict mode. What is the correct way ?

1

There are 1 answers

0
Lekhnath On

Inside of async function we must wrap a function inside runInAction utility method for mutating @observable in strict mode. Example.

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