如何使用 Mobx6 创建 RootStore
How to make RootStore with Mobx6
所以 mobx 6 出来了,我正在尝试实现这样的基本商店:
export class AuthStore {
rootStore
value
constructor(rootStore) {
makeObservable(this, {
value:observable
})
this.rootStore = rootStore
}
}
和
class RootStore {
constructor () {
this.authStore = new AuthStore(this)
}
}
const stores = new RootStore()
我收到一个错误:无法修饰未定义的 属性:'value'
但如果我将 AuthStore 放在 RootStore 之外
const authStore = new AuthStore()
一切正常..我试着阅读更多然后一次 mobx 6t 文档,但没有任何内容
想知道我做错了什么!
谢谢!
答案就在错误信息中-
Cannot decorate undefined property: 'value'
您的值是 undefined
,mobx 对此有异议。简单的解决方法是将您的值初始化为 null:
export class AuthStore {
rootStore
value = null;
constructor(rootStore) {
this.rootStore = rootStore
makeObservable(this, {
value:observable
})
}
}
很容易看出您为什么成为这个受害者 - mobx documentation itself 实际上让您相信您所做的是符合犹太教规的 -
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++
}
}
但是如果你尝试这段代码,你会得到同样的错误:|。
if i will take the AuthStore outside the RootStore every thing working fine
这让我有点震惊 - 我无法解释为什么会这样!但是 I couldn't reproduce it either - 无论在哪里初始化授权存储,我都会得到相同的行为。
更多背景信息 - mobx 在幕后使用 Object.getOwnPropertyDescriptor
来尝试计算出 value
属性 是什么 - 当值为 undefined
时,这个 returns:
Object { value: undefined, writable: true, enumerable: true, configurable: true }
所以 mobx 6 出来了,我正在尝试实现这样的基本商店:
export class AuthStore {
rootStore
value
constructor(rootStore) {
makeObservable(this, {
value:observable
})
this.rootStore = rootStore
}
}
和
class RootStore {
constructor () {
this.authStore = new AuthStore(this)
}
}
const stores = new RootStore()
我收到一个错误:无法修饰未定义的 属性:'value'
但如果我将 AuthStore 放在 RootStore 之外
const authStore = new AuthStore()
一切正常..我试着阅读更多然后一次 mobx 6t 文档,但没有任何内容
想知道我做错了什么! 谢谢!
答案就在错误信息中-
Cannot decorate undefined property: 'value'
您的值是 undefined
,mobx 对此有异议。简单的解决方法是将您的值初始化为 null:
export class AuthStore {
rootStore
value = null;
constructor(rootStore) {
this.rootStore = rootStore
makeObservable(this, {
value:observable
})
}
}
很容易看出您为什么成为这个受害者 - mobx documentation itself 实际上让您相信您所做的是符合犹太教规的 -
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++
}
}
但是如果你尝试这段代码,你会得到同样的错误:|。
if i will take the AuthStore outside the RootStore every thing working fine
这让我有点震惊 - 我无法解释为什么会这样!但是 I couldn't reproduce it either - 无论在哪里初始化授权存储,我都会得到相同的行为。
更多背景信息 - mobx 在幕后使用 Object.getOwnPropertyDescriptor
来尝试计算出 value
属性 是什么 - 当值为 undefined
时,这个 returns:
Object { value: undefined, writable: true, enumerable: true, configurable: true }