[英]Using the MobX @action decorator with async functions and .then
我正在使用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语句? 任何帮助,将不胜感激。
我是否需要将@action装饰器提供给第二个.then语句? 任何帮助,将不胜感激。
这与实际解决方案非常接近。
.then(json => this.someStateProperty = json)
应该
.then(action(json => this.someStateProperty = json))
记住action
可以在很多方面是不排斥被称为@action
。 从文档中的行动 :
action(fn)
action(name, fn)
@action classMethod
@action(name) classMethod
@action boundClassMethod = (args) => { body }
@action(name) boundClassMethod = (args) => { body }
都是将函数标记为动作的有效方法。
这是一个展示解决方案的垃圾箱: 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
没有递归地装饰任何函数作为它正在装饰的函数内的动作,这意味着你的匿名函数传递到你的诺言并不是一个真正的action
。
补充上述答案; 实际上, action
仅适用于传递给它的函数。 then
中的函数在一个单独的堆栈上运行,因此应该可以识别为单独的操作。
请注意,您还可以为操作指定名称,以便在使用这些操作时在devtools中轻松识别它们:
then(action("update objects after fetch", json => this.someStateProperty = json))
请注意,在异步方法中,您必须在等待某事后开始新的操作/事务:
@mobx.action async someAsyncFunction(args) {
this.loading = true;
var result = await fetch(`http://localhost:8080/some_url`, {
method: 'POST',
body: {
args
}
});
var json = await result.json();
@mobx.runInAction(()=> {
this.someStateProperty = json
this.loading = false;
});
}
我更喜欢不直接使用@ mobx.action / runInAction,但总是把它放在private
方法上。 让public方法调用实际更新状态的私有方法:
public someAsyncFunction(args) {
this.startLoading();
return fetch(`http://localhost:8080/some_url`, {
method: 'POST',
body: {
args
}
})
.then(res => res.json())
.then(this.onFetchResult);
}
@mobx.action
private startLoading = () => {
this.loading = true;
}
@mobx.action
private onFetchResult = (json) => {
this.someStateProperty = json;
this.loading = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.