gpt4 book ai didi

reactjs - Mobx:在没有 runInAction 的情况下更改状态仍然有效

转载 作者:行者123 更新时间:2023-12-01 12:39:42 25 4
gpt4 key购买 nike

在 mobx 中 documentation :

action only affects the currently running function, not functions that are scheduled (but not invoked) by the current function! This means that if you have a setTimeout, promise.then or async construction, and in that callback some more state is changed, those callbacks should be wrapped in action as well!

上面的意思是,我应该包装用 runInAction 更改的状态,如下所示:

class App {
@observable logined = false
@action async login(payload){
runInAction(() => {
setTimeout(() => {
this.logined = false
}, 1000)
})
}
}

上面的工作,但奇怪的是,如果我删除 runInAction block ,代码仍然有效,这种行为与文档中所说的不一致。

请检查fiddle .

最佳答案

这种行为是正确的;未观察到的数据可以随意修改,因为它不会导致进一步的副作用,请参阅:https://github.com/mobxjs/mobx/blob/master/CHANGELOG.md#310

另外,只要未启用严格模式,就始终允许在操作之外更改状态 (mobx.useStrict(true))

在文档中更好地反射(reflect)这种新行为的 PR 将不胜感激! https://github.com/mobxjs/mobx/blob/gh-pages/docs/refguide/action.md

关于reactjs - Mobx:在没有 runInAction 的情况下更改状态仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43841059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com