Subclassing
对使用子类的支持是有限制的. 最值得注意的一点是你只能 override actions/flows/computeds on prototype - you cannot override field declarations. Use override
annotation for methods/getters overriden in subclass - 见下例。 请凡事从简,并优先考虑组合(而非继承)。
import { makeObservable, observable, computed, action } from "mobx"
class Parent {
// Annotated instance fields are NOT overridable
observable = 0
arrowAction = () => {}
// Non-annotated instance fields are overridable
overridableArrowAction = action(() => {})
// Annotated prototype methods/getters are overridable
action() {}
actionBound() {}
get computed() {}
constructor(value) {
makeObservable(this, {
observable: observable,
arrowAction: action
action: action,
actionBound: action.bound,
computed: computed,
})
}
}
class Child extends Parent {
/* --- INHERITED --- */
// THROWS - TypeError: Cannot redefine property
// observable = 5
// arrowAction = () = {}
// OK - not annotated
overridableArrowAction = action(() => {})
// OK - prototype
action() {}
actionBound() {}
get computed() {}
/* --- NEW --- */
childObservable = 0;
childArrowAction = () => {}
childAction() {}
childActionBound() {}
get childComputed() {}
constructor(value) {
super()
makeObservable(this, {
// inherited
action: override,
actionBound: override,
computed: override,
// new
childObservable: observable,
childArrowAction: action
childAction: action,
childActionBound: action.bound,
childComputed: computed,
})
}
}
Limitations
- 只有定义在原型上的
action
,computed
,flow
,action.bound
可以在子类中被 重新定义。 - 不能在子类中重新注释字段(
override
除外)。 makeAutoObservable
不支持子类的使用.- 不支持扩展内置(
ObservableMap
,ObservableArray
, 等)。 - 你不能在子类中给
makeObservable
提供不同选项。 - 你不能在单个继承链中混合使用注解/装饰器。
- 所有其他限制均在此适用
TypeError: Cannot redefine property
如果你遇见这, you're probably trying to override arrow function in subclass x = () => {}
. That's not possible because all annotated fields of classes are non-configurable (see limitations). You have two options:
1. Move function to prototype and use
action.bound
annotation instead
class Parent {
// action = () => {};
// =>
action() {}
constructor() {
makeObservable(this, {
action: action.bound
})
}
}
class Child {
action() {}
constructor() {
super()
makeObservable(this, {
action: override
})
}
}
2. Remove
action
annotation and wrap the function in action manually: x = action(() => {})
class Parent {
// action = () => {};
// =>
action = action(() => {})
constructor() {
makeObservable(this, {}) // <-- annotation removed
}
}
class Child {
action = action(() => {})
constructor() {
super()
makeObservable(this, {}) // <-- annotation removed
}
}