我是TypeScript的新手,我尝试从另一个类调用操作,但出现这样的错误,也许无法通过导入使用函数,而只能通过@inject
使用函数?我可能不理解的问题是什么
@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
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存储
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();
答案 0 :(得分:1)
您导出了一个类(CommonStore
),但您尝试将其像已创建的对象一样使用。
您需要创建实例,然后才能使用它。
import commonStore from "./common";
const commonStoreInstance = new commonStore();
commonStoreInstance.setToken('token');
但是无论您import
commonStore
在哪里,都可能需要同一个实例。如果是这样,则需要在模块内部创建实例并将其导出。
赞:
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();
然后
import commonStore from "./common";
commonStore.setToken('token');