我如何用mobx和axios来写这个呢?我试图使用箭头函数来保持"this“的范围,但我可能做错了。
@action saveMode() {
axios.post('/Course/Post', { Name: "test41515"})
.then(response => {
console.log(response, this.isEditing);
this.isEditing = !this.isEditing;
this.failedValidation = [];
})
}
Uncaught (in promise) Error: [mobx] Invariant failed: Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: Course@5.isEditing
at invariant (app.bundle.js:7316)
at fail (app.bundle.js:7311)
at checkIfStateModificationsAreAllowed (app.bundle.js:7880)
at ObservableValue.prepareNewValue (app.bundle.js:5786)
at setPropertyValue (app.bundle.js:6663)
at Course.set [as isEditing] (app.bundle.js:6631)
at app.bundle.js:62336
at <anonymous>发布于 2018-01-10 23:29:18
MobX的文档中有整整一页是关于编写异步操作的。这就是开始的地方,https://mobx.js.org/best/actions.html,事实上,第一个例子就是您所面临的问题
上面的示例将引发异常,因为传递给fethGithubProjectsSomehow承诺的回调不是fetchProjects操作的一部分,因为操作只适用于当前堆栈。
考虑到您的代码片段,最简单的修复方法是使用runInAction
@action saveMode() {
axios.post('/Course/Post', { Name: "test41515"})
.then(response => {
runInAction(() => {
console.log(response, this.isEditing);
this.isEditing = !this.isEditing;
this.failedValidation = [];
});
})
}https://stackoverflow.com/questions/48197656
复制相似问题