子類別化
子類別化受到限制。最值得注意的是,您只能**覆寫原型上的動作/流程/計算屬性** - 您不能覆寫* 欄位宣告*。對於在子類別中覆寫的方法/ getter,請使用 override
註釋 - 請參閱下面的範例。盡量保持程式碼簡潔,並優先考慮組合而不是繼承。
import { makeObservable, observable, computed, action, override } 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,
})
}
}
限制
- 只有**在原型上**定義的
action
、computed
、flow
、action.bound
可以被子類別**覆寫**。 - 欄位不能在子類別中重新註釋,除非使用
override
。 makeAutoObservable
不支援子類別化。- 不支援擴展內建類型(
ObservableMap
、ObservableArray
等)。 - 您不能在子類別中為
makeObservable
提供不同的選項。 - 您不能在單一繼承鏈中混合註釋/裝飾器。
- 所有其他限制也適用
TypeError: 無法重新定義屬性
如果您看到這個錯誤,您可能正在嘗試在子類別 x = () => {}
中**覆寫箭頭函式**。這是不可行的,因為類別的**所有已註釋**欄位都是**不可設定的**(請參閱限制)。您有兩個選擇
1. 將函式移至原型,並改用 action.bound
註釋
class Parent {
// action = () => {};
// =>
action() {}
constructor() {
makeObservable(this, {
action: action.bound
})
}
}
class Child {
action() {}
constructor() {
super()
makeObservable(this, {
action: override
})
}
}
2. 移除 action
註釋,並手動將函式包裝在 action 中:x = action(() => {})
class Parent {
// action = () => {};
// =>
action = action(() => {})
constructor() {
makeObservable(this, {}) // <-- annotation removed
}
}
class Child {
action = action(() => {})
constructor() {
super()
makeObservable(this, {}) // <-- annotation removed
}
}