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