You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中如何基于异步函数执行结果条件阻止路由跳转

问题原因

当前代码存在两个核心问题:

  • uploadDocument内部的.catch()捕获到请求错误后,仅做了提示就结束执行,既没有向外抛出异常,也没有返回状态标识,相当于把错误完全内部消化。外层await只会拿到resolve状态的undefined,永远无法感知请求失败。
  • 原生fetch只有在网络故障、请求无法发出的场景下才会触发reject,接口返回4xx、5xx这类HTTP错误状态时默认会走resolve逻辑,原有代码就算接口返回500错误,也会误弹成功提示。
修复代码

第一步:改造上传函数,保留内部提示同时向外返回执行状态

把原有链式then/catch改成try/catch写法,补全HTTP错误判断,处理完提示后返回明确的成功/失败标识,外层即可拿到结果做逻辑判断:

export const uploadDocument = async (url: UploadURLs, file: File) => {
  const formData = new FormData();
  formData.append("file", file);
  try {
    const response = await fetch(`${someEndpoint}`, {
      method: "POST",
      body: formData,
    });
    // 拦截4xx、5xx等HTTP错误状态
    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}`);
    }
    notify(`Awesome, it worked.`, "success");
    // 返回成功标识供外层判断
    return { success: true };
  } catch (error) {
    notify("An error occurred.", "error");
    // 返回失败标识供外层判断
    return { success: false };
  }
};

第二步:调整提交逻辑,根据返回结果决定是否跳转

拿到上传函数的返回值后,仅在成功状态下执行路由跳转:

const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  const uploadResult = await uploadDocument("certificate", file);
  if (uploadResult.success) {
    router.push(nextPage);
  }
};
可选写法(异常捕获风格)

如果你更习惯用try/catch做流程控制,也可以在上传函数的catch块处理完提示后重新抛出错误,调用处通过捕获异常判断失败:

// 上传函数catch块调整
catch (error) {
  notify("An error occurred.", "error");
  throw error; // 处理完提示后重新抛出异常
}

// 提交逻辑调整
const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  try {
    await uploadDocument("certificate", file);
    // 无异常说明上传成功,执行跳转
    router.push(nextPage);
  } catch (error) {
    // 上传失败,内部已弹提示,此处无需额外逻辑,自然不会触发跳转
  }
};

内容的提问来源于stack exchange,提问作者Andy Hoffman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:57:14