问题描述
所以我有两个模型:RootStore
和 ProjectsModel
:
const RootStore = types
.model({
user: types.maybeNull(User),projects: ProjectsModel,})
在 ProjectsModel
中,我有一个需要 root 用户属性的操作
const ProjectsModel = types
.model({...})
.actions((self) => ({
loadStarred: flow(function* () {
const u = getParent(self).user; < here
//....
我正在使用 TS 而 TS 不喜欢它:
Property 'user' does not exist on type '(object & IStateTreeNode<IAnyComplexType>) | IStateTreeNode<IAnyStateTreeNode>'.
好吧,我想我需要输入 getParent?
const u = getParent<Instance<typeof RootStore>>(self).user;
哦不,它更不喜欢它
'ProjectsModel' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
'RootStore' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
自参考在哪里?如何正确键入 getParent?
解决方法
我认为你只需要在那里使用 <typeof RootStore>
:
import { types,getParent } from 'mobx-state-tree';
const ProjectsModel = types
.model({
something: types.string
})
.actions((self) => ({
loadStarred: () => {
const { user } = getParent<typeof RootStore>(self);
// typed as User,no errors
console.log(user?.name);
}
}));
const User = types.model({
name: types.string
});
const RootStore = types.model({
user: types.maybeNull(User),projects: ProjectsModel
});
,
这是由于循环引用而发生的。打破这个并试图跳过这个问题的一种方法是
./root.ts
const RootStore = types
.model({
user: types.maybeNull(User),projects: ProjectsModel,})
./iRoot.ts
export type IRootStore = Instance<typeof RootStore>
./projects.ts
const ProjectsModel = types
.model({...})
.actions((self) => ({
loadStarred: flow(function* () {
const u = getParent<IRootStore>(self).user; < here
//....
也有手动创建界面的方法,如下所示:
./root.ts
const RootStore = types
.model({
user: types.maybeNull(User),})
./type.ts
export interface IRootStore {
user: IUser | null,projects: IProjectsModel,}
./projects.ts
const ProjectsModel = types
.model({...})
.actions((self) => ({
loadStarred: flow(function* () {
const u = getParent<IRootStore>(self).user; < here
//....
我不喜欢这种方法,因为它需要开发人员保持商店和界面同步。