【问题标题】:Mobx changing observable values outside of actionMobx 在动作之外改变可观察值
【发布时间】:2017-10-29 08:49:46
【问题描述】:

我收到以下错误:

proxyConsole.js:54 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: ObservableObject@1.items
    at invariant (mobx.module.js:2326)
    at fail (mobx.module.js:2321)
    at checkIfStateModificationsAreAllowed (mobx.module.js:2890)
    at ObservableValue../node_modules/mobx/lib/mobx.module.js.ObservableValue.prepareNewValue (mobx.module.js:796)
    at setPropertyValue (mobx.module.js:1673)
    at Object.set [as items] (mobx.module.js:1641)
    at Store.js:41
    at <anonymous>

但我将函数包装在 action 中,所以我有点困惑:

import { observable, useStrict, action } from 'mobx';
import Services from './Services';

// ...

getAllTodos: action(() => {

    Services.getAllTodos()
    .then((response) => {

        state.items = response.data;

    }).catch((error) => {
        console.error(error);
    });

}),

Services.js

// ...

getAllTodos () {
    return axios.get(root + '/items/');
}

我在这里错过了什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 mobx


    【解决方案1】:

    一个改变 observables 的函数需要被包裹在 action 中,所以也可以在回调中使用它:

    getAllTodos: action(() => {
    
      Services.getAllTodos()
      .then(action((response) => {
        state.items.replace(response.data);
      })).catch((error) => {
        console.error(error);
      });
    })
    

    【讨论】:

    • 不确定我是否理解。这不正是@Tiwaz89 所做的,但它仍然没有工作吗?
    • @oriharel 请注意 Tiwaz89 的 getAllTodos 方法是一个动作,但在我的回答中,赋予then 的函数也是一个动作。
    【解决方案2】:

    如 MobX 文档 here 中所述:

    动作包装器/装饰器只影响当前运行的函数,不影响当前函数调度(但未调用)的函数!这意味着,如果您有一个 setTimeout、promise.then 或异步构造,并且在该回调中更改了更多状态,那么这些回调也应该包含在操作中!

    因此,除了父函数之外,您还必须将预定的promise.then 包装在一个动作中。 (请注意,您只能在类级函数上使用@action

    有两种方法:

    action(
      asyncFunction().then(
        action((args) => {
          // Your function body here
        })
      )
    )
    

    --或--

    使用@action.bound

    @action
    asyncFunction().then(
      yourStateModifyingFunction();
    )
    
    @action.bound
    yourStateModifyingFunction() {
      // Your function body here
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多