首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不变失败:不允许更改可观察到的外部操作值

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

Stack Overflow用户
提问于 2018-01-10 23:18:26
回答 1查看 2.5K关注 0票数 0

我如何用mobx和axios来写这个呢?我试图使用箭头函数来保持"this“的范围,但我可能做错了。

代码语言:javascript
复制
@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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-10 23:29:18

MobX的文档中有整整一页是关于编写异步操作的。这就是开始的地方,https://mobx.js.org/best/actions.html,事实上,第一个例子就是您所面临的问题

上面的示例将引发异常,因为传递给fethGithubProjectsSomehow承诺的回调不是fetchProjects操作的一部分,因为操作只适用于当前堆栈。

考虑到您的代码片段,最简单的修复方法是使用runInAction

代码语言:javascript
复制
@action saveMode() {

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

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48197656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档