Redux中使用async/await遇‘async是保留字’错误,求代码排查
排查Redux异步Action的"async是保留字"错误
我来帮你拆解下问题根源,你的代码写法混淆了Redux Thunk Action Creator的结构,同时存在语法格式错误,才导致了这个报错:
错误原因分析
Redux Thunk要求Action Creator返回一个能接收dispatch的函数,你把async标记错了位置,同时第二个写法的箭头函数语法完全不符合规范:
第一个写法的核心问题
export async function getCredit(){ return dispatch => { try { const creditInfo = await axios.get(`/credit`) } catch (err) { dispatch(errorMsg(err.data.msg)) } // 这里还有个变量错误:使用了未定义的res,应该是creditInfo if(creditInfo.result === 200 && res.data.status === 1) { dispatch({ type: GET_CREDIT, payload: creditInfo.data }) } } }
你把async加在了外层的Action Creator函数上,但外层函数返回的是一个普通的dispatch => {}函数——真正执行异步逻辑的是这个内部函数,你却没给它标记async,所以JS会报错;而且外层的async完全多余,因为Action Creator返回的是Thunk函数,不是Promise。
第二个写法的语法错误
export async getCredit() => dispatch => { ... }
这是典型的箭头函数语法错误:async必须放在箭头函数参数列表的前面,同时不能用async getCredit() =>这种写法,正确的箭头函数声明需要先绑定到变量/常量上。
正确的写法示例
你需要把async标记在Action Creator返回的那个接收dispatch的函数上,同时修正代码里的其他小问题:
函数声明式写法
export function getCredit() { // 真正执行异步逻辑的是这个内部函数,必须标记为async return async (dispatch) => { try { const creditInfo = await axios.get(`/credit`); // 修正变量错误,加可选链避免空值报错 if(creditInfo.result === 200 && creditInfo.data?.status === 1) { dispatch({ type: GET_CREDIT, payload: creditInfo.data }); } } catch (err) { // axios错误对象的响应数据存在于response.data中,做容错处理 dispatch(errorMsg(err.response?.data?.msg || '获取信用信息失败')); } }; }
箭头函数式写法
export const getCredit = () => async (dispatch) => { try { const creditInfo = await axios.get(`/credit`); if(creditInfo.result === 200 && creditInfo.data?.status === 1) { dispatch({ type: GET_CREDIT, payload: creditInfo.data }); } } catch (err) { dispatch(errorMsg(err.response?.data?.msg || '请求失败')); } };
额外提醒
- 确保你已经在Redux store中正确配置了Thunk中间件,否则返回函数的Action不会被正确处理
- 异步请求的错误处理要考虑到网络异常、无响应数据等情况,避免出现未捕获的错误
- 变量命名和使用要保持一致,避免出现未定义变量的低级错误
内容的提问来源于stack exchange,提问作者Jamie Aden
相关产品推荐
相关产品推荐

