【发布时间】:2021-06-03 18:26:23
【问题描述】:
我实际上正在将一些代码迁移到打字稿,所以我对所有这些类型的东西都是新手。当我将 redux-thunk 与常规 javascript 一起使用时,dispatch 方法返回了一个可以帮助我处理错误和东西的承诺。行动是这样的:
export const login = ({email, password}) => {
return async function (dispatch) {
try {
const result = await api.post(`/auth/login`, {username, password});
return dispatch({type: 'set_user_session', payload: result.data});
} catch (err) {
throw (err.response && err.response.data) || {code: err};
}
};
};
然后我使用 useDispatch 钩子正常调用:
const dispatch = useDispatch();
...
dispatch(login({username: "admin", password: "adminpassword1"}))
.then(d => console.log("ok"))
.catch(err => console.log(err));
现在我将代码迁移到 typescript,操作现在看起来像这样:
export const login = ({username, password}: Credentials): ThunkAction<Promise<Action>, {}, {}, AnyAction> => {
// Invoke API
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>): Promise<Action> => {
try {
const result = await api.post(`/auth/login`, {username, password});
return dispatch({type: 'set_user_session', payload: result.data});
} catch (err) {
console.log(err);
throw (err.response && err.response.data) || {code: err};
}
}
}
这执行没有问题,但如果我尝试处理这个:
dispatch(login({username: "admin", password: "adminpassword1"}))
.then(d => console.log("ok"))
.catch(err => console.log(err));
我收到此错误:
TS2339: Property 'then' does not exist on type 'ThunkAction >, {}, {}, AnyAction>'
我尝试阅读有关 Redux 中类型的部分,但我找不到正确的方法来声明此调度函数按我的需要工作。
https://redux.js.org/recipes/usage-with-typescript
更糟糕的是,我在执行操作后收到此运行时错误:
Possible Unhandled Promise Rejection (id: 0):
所以承诺就在某个地方。
【问题讨论】:
-
这是一个已知问题,我知道它已得到修复,但我认为它尚未发布? github.com/reduxjs/redux-thunk/issues/275github.com/reduxjs/redux-thunk/issues/231
标签: typescript redux redux-thunk