我有两家商店: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>
}
所以有两种错误:
observables
的{{1}}访问ProfileStore
时FormStore
的{{1}}中更新observables
时 ProfileStore
运行正常
两个通过FormStore
注入的商店,但是它们的商店没有嵌套。我将它们嵌套,因为我想从FormStore
React.useContext
这些错误是什么意思?如何解决它们?
答案 0 :(得分:0)
实际上不是答案:)但是我使用的解决方案
export class ProfileStore {
@observable editing;
@observablt userProfile: UserProfile;
...
}
仅此而已-不再使用两个商店,而是现在有了一个商店,我很高兴该解决方案有效。我以为错误是我忘记在get
上写toJson
。如果将来我遇到相同的错误并理解为什么会发生。我会尽量不要忘记更新此答案。