表单提交后用router.push重定向遇Network Error,延迟数秒才完成跳转
问题分析与解决方案
核心问题
- 冗余代码干扰流程:try/catch块之后的同步代码会无条件执行,覆盖try块中设置的状态,甚至可能在路由跳转后仍修改组件状态,引发异常。
- 拼写错误引发未捕获错误:代码中
updateCompilance是拼写错误(正确应为updateCompliance),若该函数未定义或调用异常,会触发未被try/catch捕获的错误。 - 网络错误未被正确捕获:若API调用函数内部使用的请求库(如axios)存在全局拦截器,未将错误正确reject为Error实例,会导致try/catch无法捕获异常。
修复步骤
- 移除try/catch后的冗余状态更新代码:将
setIsComplete(true)移至try块的路由跳转前,确保只有API调用全部成功时才标记表单完成。 - 修复函数拼写错误:修正
updateCompilance为updateCompliance,避免引用不存在的函数。 - 增强错误捕获与日志:在catch块中打印完整错误详情,确保能定位问题;同时检查API调用函数是否正确抛出Error类型错误。
修改后的代码
const handleFinish = async () => { setIsLoading(true); if (!formState.data.privateMetadata.agreement) { setAlertMessage('Please confirm the terms and conditions'); setShowAlert(true); setIsLoading(false); return; } const user = constructUser(formState); try { console.log('Benutzerdaten werden aktualisiert...'); await updateUserData(locale, user); console.log('Vor- und Nachname werden aktualisiert...'); await updateFirstAndLastName(locale, user); console.log('Compliance-Status wird aktualisiert...'); await updateCompliance(user.id); // 修复拼写错误 setAlertMessage(''); setShowAlert(false); setIsLoading(false); setIsComplete(true); // 仅在成功时标记完成 console.log('Weiterleitung zu:', `/${locale}/welcome`); router.push(`/${locale}/welcome`); } catch (error) { console.error('Fehler während der Anmeldung:', error); console.error('错误详情:', JSON.stringify(error, Object.getOwnPropertyNames(error))); // 打印完整错误信息 setAlertMessage('Bei der Anmeldung ist ein Fehler aufgetreten'); setShowAlert(true); setIsLoading(false); } };
额外排查点
- 检查浏览器控制台的网络请求,确认哪个API调用触发了网络错误(如跨域、404/500状态码)。
- 确认API调用函数内部是否正确处理了请求错误:例如使用axios时,需确保在拦截器中
return Promise.reject(error),否则错误不会被外层try/catch捕获。
内容的提问来源于stack exchange,提问作者Demian
相关产品推荐
相关产品推荐

