不变失败:不允许在操作之外更改观察到的可观察值

Invariant failed: Changing observed observable values outside actions is not allowed

如何使用 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>

MobX 在他们的文档中有一整页是关于编写异步操作的。这就是开始的地方,https://mobx.js.org/best/actions.html,事实上,第一个例子正是你在注释

中遇到的问题

The above example would throw exceptions, as the callbacks passed to the fethGithubProjectsSomehow promise are not part of the fetchProjects action, as actions only apply to the current stack.

鉴于您的代码段,最简单的解决方法是使用 runInAction

@action saveMode() {

  axios.post('/Course/Post', { Name: "test41515"})
    .then(response => {
      runInAction(() => {
        console.log(response, this.isEditing);
        this.isEditing = !this.isEditing;
        this.failedValidation = [];
      });
    })

}