React中try catch代码块为何无法执行?
问题原因
你MyComponent里的try/catch不生效,核心问题出在handleRegister函数里:它自己把请求错误捕获了,但没把错误重新抛出来。
async函数里如果catch了错误却不throw,那这个函数返回的Promise就会是resolved(成功)状态,上层await之后自然不会进入catch分支,所以你的setStep(1)永远不会执行。
修复方案
给你两种实用的修复方式,选哪种都行:
方式一:让handleRegister把错误抛出来
修改httpService里的handleRegister,处理完toast提示后,把错误重新抛出,这样上层的try/catch就能接住:
export const handleRegister = async (user: User): Promise<void> => { try { await axios.post(`${config.apiEndPoint}/auth/register`, user, header); } catch ({ response }) { handleExpectedError(response); // 关键:重新抛出错误,让上层catch能捕获 throw response; } };
这样注册失败时,既会弹出toast错误提示,上层的catch块也会执行setStep(1),停留在第一步。
方式二:让handleRegister返回成功/失败状态
如果不想抛错误,就让handleRegister返回布尔值,上层根据返回值判断下一步:
// 先改httpService的handleRegister export const handleRegister = async (user: User): Promise<boolean> => { try { await axios.post(`${config.apiEndPoint}/auth/register`, user, header); return true; // 成功返回true } catch ({ response }) { handleExpectedError(response); return false; // 失败返回false } }; // 再改MyComponent里的handleNextStep const handleNextStep = async (value: any) => { if (step === 1) { const registerSuccess = await handleRegister(value); if (!registerSuccess) { setStep(1); return; } setStep(step + 1); await handeGetActivateCode({ email: value.email }); } if (step !== 1) return setStep(step - 1); };
额外提醒
handeGetActivateCode请求也可能失败,最好给它也加个错误处理,避免后续流程出问题。- 检查Formik的
onSubmit里的terms状态,确保用户勾选后才会触发handleNextStep。
内容的提问来源于stack exchange,提问作者Solid1
相关产品推荐
相关产品推荐

