簡體   English   中英

Mobx 在動作之外改變可觀察值

[英]Mobx changing observable values outside of action

我收到以下錯誤:

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);
    });

}),

服務.js

// ...

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

我在這里缺少什么?

一個改變 observables 的函數需要被包裝在action ,所以也可以在回調中使用它:

getAllTodos: action(() => {

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

正如此處的 MobX 文檔所述:

動作包裝器/裝飾器僅影響當前運行的函數,而不影響當前函數調度(但未調用)的函數! 這意味着如果您有 setTimeout、promise.then 或異步構造,並且在該回調中更改了更多狀態,則這些回調也應包含在 action 中!

因此,除了父函數之外,您還必須將預定的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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM