问题
使用 mobx 的 decorate
时候,报了以下错误
Attempted import error: 'decorate' is not exported from 'mobx'.
说明下背景,我使用的 mobx 版本是 6.0,尝试使用 mobx-react,mobx-react-lite,mobx-decorate 等库都无法实现。
原因
decorate
API 在 mobx 6.0 中已经被废弃,可以使用 makeObservable
API 来代替。在 class
的构造函数中使用,参数跟 decorate
API 一样。
解决
方法一,使用 makeObservable
来代替
import { makeObservable, observable, computed, action } from "mobx";
class Doubler {
value;
constructor(value) {
makeObservable(this, {
value: observable,
double: computed,
increment: action,
});
this.value = value;
}
get double() {
return this.value * 2;
}
increment() {
this.value++;
}
}
方法二,使用 makeAutoObservable
来代替
import { makeAutoObservable } from "mobx";
class Timer {
secondsPassed = 0;
constructor() {
makeAutoObservable(this);
}
increaseTimer() {
this.secondsPassed += 1;
}
}