【问题标题】:Invariant failed: Changing observed observable values outside actions is not allowed不变量失败:不允许在操作之外更改观察到的可观察值
【发布时间】:2018-01-10 23:18:26
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs ecmascript-6 mobx


    【解决方案1】:

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

    上述示例会抛出异常,因为传递给 fethGithubProjectsSomehow 承诺的回调不是 fetchProjects 操作的一部分,因为操作仅适用于当前堆栈。

    鉴于您的 sn-p,最简单的解决方法是使用 runInAction

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2014-03-24
      • 2015-11-20
      • 1970-01-01
      • 2022-07-25
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多