2017-10-29 107 views
2

我收到以下错误之外的可观察值:Mobx变化作用

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: [email protected] 
    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/'); 
} 

我在这里错过了什么?

回答

2

需要被包裹在action该改变可观察的函数,因此使用它的回调,以及:

getAllTodos: action(() => { 

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