javascript - 如何使用 mobx 让 autorun 与 runInAction 一起工作?
问题描述
尝试学习 mobx 和 runInAction,但很难理解为什么 autorun 在以下示例中没有调用我的回调:
class FooClass {
// constructor() {
// this.fooMethod();
// }
@observable myBool = false;
async fooMethod() {
await new Promise(r => setTimeout(r, 1000));
runInAction(() => this.myBool = true); // <--- myBool: true is never logged to the console. why?
await new Promise(r => setTimeout(r, 3000));
runInAction(() => this.myBool = false); // <--- also not logged
}
}
let foo = new FooClass();
foo.fooMethod();
autorun(() => console.log("myBool:", foo.myBool));
将 TypeScript 和 babel 与装饰器一起使用。
据我了解,如果您不在标记为操作的方法内时想要更改一些可观察对象,可以使用 runInAction(...) 吗?
为什么我的脚本不起作用?
解决方案
你可能正在使用 MobX v6 并且它的 api 稍微改变了一点,你现在需要在构造函数中添加makeAutoObservable
或makeObservable
调用,像这样:
import { autorun, makeAutoObservable, observable, runInAction } from 'mobx';
class FooClass {
constructor() {
makeAutoObservable(this);
autorun(() => console.log('myBool:', this.myBool));
this.fooMethod();
}
// You can actually remove decorator here if you use `makeAutoObservable`
@observable myBool = false;
async fooMethod() {
await new Promise((r) => setTimeout(r, 1000));
runInAction(() => (this.myBool = true)); // it will be logged now
await new Promise((r) => setTimeout(r, 3000));
runInAction(() => (this.myBool = false)); // it will be logged now too
}
}
new FooClass();
推荐阅读
- typescript - loopback 4.0中如何使用存储组件?
- javascript - 减少对象和嵌套对象:javascript
- asp.net-core - 使用 Http.sys 和服务结构的 asp.net 核心上的通配符证书问题
- apache-spark-sql - 从复杂的嵌套 json 中获取值
- jquery - Jquery Sortable不在django中拖放列表项
- python - 尝试连接多个 IP 地址并获取第一个成功的
- node.js - Angular 应用程序使用 express-session 对端口 3000 和端口 4200 进行身份验证
- javascript - 如何有条件地显示选中
- vba - 西里尔语到拉丁语转换器 - 某些字符在某些计算机上无法识别
- sql - 使用控制参数进行过滤时,GridView 消失