[英]Property does not exist on type 'typeof CommonStore'. mobx-react
I am new to TypeScript and I try to call an action from another class and I get such an error, maybe it's not possible to use functions through import but only through @inject
? 我是TypeScript的新手,我尝试从另一个类调用操作,但出现这样的错误,也许无法通过import使用函数,而只能通过@inject
? What could be the problem I do not understand 我可能不明白的问题是什么
@types
: PS已建立@types
: "@types/react": "^16.8.22",
"@types/react-dom": "^16.8.4",
"@types/react-router-dom": "^4.3.4",
import {
observable,
action,
autorun,
set,
toJS,
extendObservable
} from "mobx";
import commonStore from "./common";
export default class Authentication {
@action login = async() => {
this.inProgress = true;
this.errors = undefined;
try {
const token = await requestApi({
method: "post",
url: `/auth/login`,
data: {
login: this.username,
pass: this.password
}
});
commonStore.setToken(token); // Property 'setToken' does not exist on type 'typeof CommonStore'
} catch (error) {
axiosErrorHandler(error);
}
}
}
CommonStore CommonStore的
export default class CommonStore {
@observable token = window.localStorage.getItem("jwt");
constructor() {
reaction(
() => this.token,
token => {
if (token) {
localStorage.setItem("jwt", token);
} else {
localStorage.removeItem("jwt");
}
}
);
}
@action setToken(token: string) {
this.token = token;
}
}
index.ts store index.ts商店
import Authentication from "./models/authentication";
import Common from "./models/common";
class ObservableListStore {
@observable authentication = new Authentication();
@observable common = new Common();
}
export const store = new ObservableListStore();
You exported a class ( CommonStore
) but you're trying use it like an object that already created. 您导出了一个类( CommonStore
),但您尝试将其像已创建的对象一样使用。
You need to create the instance and then you could use it. 您需要创建实例,然后才能使用它。
import commonStore from "./common";
const commonStoreInstance = new commonStore();
commonStoreInstance.setToken('token');
But probably you want the same instance wherever you import
the commonStore
. 但是,无论您在哪里import
commonStore
可能需要同一个实例。 If so, you need to create the instance inside the module and export that. 如果是这样,则需要在模块内部创建实例并将其导出。
Like this: 像这样:
class CommonStore {
@observable token = window.localStorage.getItem("jwt");
constructor() {
reaction(
() => this.token,
token => {
if (token) {
localStorage.setItem("jwt", token);
} else {
localStorage.removeItem("jwt");
}
}
);
}
@action setToken(token: string) {
this.token = token;
}
}
export const commonStore = new CommonStore();
Then 然后
import commonStore from "./common";
commonStore.setToken('token');
https://k94n.com/es6-modules-single-instance-pattern https://k94n.com/es6-modules-single-instance-pattern
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.