我正在使用MobX 2.2.2来尝试在异步动作中改变状态.我的MobX的useStrict设置为true.
@action someAsyncFunction(args) { fetch(`http://localhost:8080/some_url`,{ method: 'POST',body: { args } }) .then(res => res.json()) .then(json => this.someStateProperty = json) .catch(error => { throw new Error(error) }); }
我得到:
Error: Error: [mobx] Invariant Failed: It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended
我需要将@action装饰器提供给第二个.then语句吗?任何帮助将不胜感激.
解决方法
@H_403_13@Do I need to supply the @action decorator to the second .then statement? Any help would be appreciated.
这是非常接近实际的解决方案.
.then(json => this.someStateProperty = json)
应该
.then(action(json => this.someStateProperty = json))
记住,行动可以以许多方式被称为@action不排除.从the docs on action:
动作(fn)
> action(name,fn)
> @action classMethod
> @action(name)classMethod
> @action boundClassMethod =(args)=> { 身体 }
> @action(name)boundClassMethod =(args)=> { 身体 }
这是一个解决方案:http://jsbin.com/peyayiwowu/1/edit?js,output
mobx.useStrict(true); const x = mobx.observable(1); // Do async stuff function asyncStuff() { fetch('http://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) // .then((objects) => x.set(objects[0])) BREAKS .then(mobx.action((objects) => x.set(objects[0]))) } asyncStuff()
至于为什么你的错误实际上发生了,我猜测,顶级的@action不递归地装饰任何函数作为它的装饰的函数内的动作,这意味着你的匿名函数传递到你的承诺不是一个真正的行动.