我有两个存储:formStore
和profileStore
FormStore
export class ProfileFormStore {
@observable editing = false;
profileStore = new ProfileStore(this.roleId);
originalValue?: ApiModel | null;
@action.bound
startEdit() {
// this.originalValue = this.profileStore.toJson();
/* if uncomment above, next error thrown
RangeError: Maximum call stack size exceeded
at initializeInstance (mobx.module.js:391)
at ProfileStore.get (mobx.module.js:381)
at ProfileStore.get
*/
this.editing = true;
}
}
ProfileStore
export class ProfileStore {
@observable userProfile: ApiModel = {
userProfile: {
newsAndUpdates: false,
email: "",
phone: "",
lastName: "",
firstName: "",
},
};
@observable email = "";
@action.bound
fetch() {
// this.fromJson(this.actions.fetch());
console.log("start");
this.email = "qwe";
console.log("end");
}
@computed
toJson(): ApiModel {
return {
userProfile: {
firstName: this.userProfile.userProfile.firstName,
lastName: this.userProfile.userProfile.lastName,
phone: this.userProfile.userProfile.phone,
email: this.userProfile.userProfile.email,
newsAndUpdates: this.userProfile.userProfile.newsAndUpdates,
},
};
}
}
我想使用上下文
const formStore = new ProfileFormStore();
export const profileFormContext = React.createContext({
formStore,
profileStore: formStore.profileStore,
});
export const useProfileContext = () => React.useContext(profileFormContext);
并且有两个组件:form
和formControl
const controls = {
admin: (<><ProfileName /><Email /></>),
user: (<><ProfileName /></>)
};
export const Form = () => {
const { formStore, profileStore } = useProfileContext();
// this.fromJson(this.actions.fetch()); // if uncomment throws 'Missing option for computed get'
return <form>(controls.admin)</form>
}
export const ProfileName = () => {
const { formStore, profileStore } = useProfileContext();
formStore.startEdit(); // check form store, when assigning from profileStore get overflow error
return formStore.editing ? <input value='test' /> : <label>Test</label>
}
所以有两种错误:
- 从属于
FormStore
的ProfileStore
访问observables
时 - 在作为
FormStore
一部分的ProfileStore
中更新observables
时
FormStore
工作良好的
通过React.useContext
注入的两个存储都遵循了以下示例https://mobx-react.js.org/recipes-context,但是它们的存储没有嵌套。我让它们嵌套,因为我想从formStore
访问profileStore
这些错误是什么意思?如何修复它们?
实际上这不是答案:(但我使用的解决方案是
export class ProfileStore {
@observable editing;
@observablt userProfile: UserProfile;
...
}
仅此而已,我很高兴这个解决方案正在发挥作用,而不是使用两个商店,现在有一个商店。我想那个错误是我忘记在toJson
处写入get
。如果将来我遇到同样的错误并理解为什么会发生。我会尽量不要忘记更新这个答案。