我有以下商店:
import { observable, action } from "mobx";
class UiStore {
@observable string;
constructor() {
this.string = "My string";
}
@action
setString = value => {
this.string = value;
};
}
export default UiStore;
我开玩笑地运行一个简单的测试:
import UiStore from "./UiStore";
describe("uiStore", () => {
it("setString sets string to the passed value", () => {
const uiStore = new UiStore();
uiStore.setString("blah");
expect(uiStore.string).toBe("blah");
});
});
但是我收到以下错误:
类型错误:uiStore.setString 不是函数
当我卸下@action
装饰器时,测试将通过。但根据 mobx 文档,当函数修改状态时,@action
装饰器会显著提高性能。有人知道测试mobx@actions的方法吗?
不使用箭头函数可以解决此问题:
import { observable, action } from "mobx";
class UiStore {
@observable string;
constructor() {
this.string = "My string";
}
@action
setString(value) {
this.string = value;
}
}
export default UiStore;
不知道为什么...
为了使装饰器使用类字段方法,您必须确保在使用transform-decorators-legacy
和transform-class-properties
插件时将它们按正确的顺序放在.babelrc
中,例如:
不對 ✖
"plugins": [
"transform-class-properties",
"transform-decorator-legacy",
]
正确 ✔
"plugins": [
"transform-decorator-legacy",
"transform-class-properties",
]
或者,您可以在类方法上使用@action.bound
装饰器,这将绑定它,就好像它是一个类字段方法一样,正如 Miha 在他的答案中所建议的那样。