MobX 自动运行没有得到它应该的依赖
MobX autorun doesn't get dependency it should
我从 https://mobx.js.org/understanding-reactivity.html
中获取的代码
import { makeAutoObservable, autorun, getDependencyTree } from "mobx";
class Message {
title;
author;
likes;
constructor(title, author, likes) {
makeAutoObservable(this);
this.title = title;
this.author = author;
this.likes = likes;
}
updateTitle(title) {
this.title = title;
}
}
let message = new Message("Foo", { name: "Michel" }, ["Joe", "Sara"]);
const disposer = autorun(() => {
console.log(message.title);
});
console.log(getDependencyTree(disposer));
message.updateTitle("Bar");
message.updateTitle("gasdg");
但在控制台中我得到了这个:
Foo
index.js:114 {name: 'Autorun@2'}
它没有将 message.title
作为依赖项,请帮助我理解原因!
By default make(Auto)Observable
仅支持已定义的属性,因此您需要在构造函数中定义每个 属性 或使其可为空:author = null
,或添加默认值 likes = 0
:
class Message {
// Or add default values here
title = '';
author = null;
likes = 0;
constructor(title, author, likes) {
// Initialise properties as first thing
this.title = title;
this.author = author;
this.likes = likes;
makeAutoObservable(this);
}
updateTitle(title) {
this.title = title;
}
}
或者您可能想尝试重新配置 how class properties initialisation works,使用 useDefineForClassFields
TS 编译器标志:
"compilerOptions": {
"useDefineForClassFields": true
},
我从 https://mobx.js.org/understanding-reactivity.html
中获取的代码import { makeAutoObservable, autorun, getDependencyTree } from "mobx";
class Message {
title;
author;
likes;
constructor(title, author, likes) {
makeAutoObservable(this);
this.title = title;
this.author = author;
this.likes = likes;
}
updateTitle(title) {
this.title = title;
}
}
let message = new Message("Foo", { name: "Michel" }, ["Joe", "Sara"]);
const disposer = autorun(() => {
console.log(message.title);
});
console.log(getDependencyTree(disposer));
message.updateTitle("Bar");
message.updateTitle("gasdg");
但在控制台中我得到了这个:
Foo
index.js:114 {name: 'Autorun@2'}
它没有将 message.title
作为依赖项,请帮助我理解原因!
By default make(Auto)Observable
仅支持已定义的属性,因此您需要在构造函数中定义每个 属性 或使其可为空:author = null
,或添加默认值 likes = 0
:
class Message {
// Or add default values here
title = '';
author = null;
likes = 0;
constructor(title, author, likes) {
// Initialise properties as first thing
this.title = title;
this.author = author;
this.likes = likes;
makeAutoObservable(this);
}
updateTitle(title) {
this.title = title;
}
}
或者您可能想尝试重新配置 how class properties initialisation works,使用 useDefineForClassFields
TS 编译器标志:
"compilerOptions": {
"useDefineForClassFields": true
},