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

React中axios请求完成后swal弹窗不触发、history路由跳转失效如何解决?

问题可能的原因如下:

  • 缺少异常捕获逻辑
    你当前的代码仅编写了try成功分支,没有配套catch块捕获后续操作抛出的异常,一旦swal调用或者路由跳转逻辑出错会直接静默终止。建议补充异常捕获打印错误信息排查:
const saveChanges = async () => {
  try{
    const response = await axios.post('http://localhost:3000/operation', form);
    dispatch({
      type: 'ADD_OPERATION',
      operation: response.data
    });
    swal('YAY!', 'The operation was successfully added', 'success');
    props.history.push('/');
  } catch (err) {
    console.error('操作失败', err) // 此处可打印错误排查具体问题
  }
}
  • 路由API不兼容/未注入
    这是最常见的原因:
    1. 如果你使用的是react-router v5及更早版本:检查当前组件是否是路由直接渲染的组件,如果是嵌套组件需要用withRouter高阶组件包裹,才能在props上拿到注入的history对象
    2. 如果你使用的是react-router v6及以上版本:props.historyAPI已被完全废弃,需要使用useNavigate钩子实现跳转,修改示例如下:
import { useNavigate } from 'react-router-dom'

// 组件内部
const navigate = useNavigate()
const saveChanges = async () => {
  try{
    // 原有接口请求、dispatch逻辑不变
    swal('YAY!', 'The operation was successfully added', 'success');
    navigate('/') // 代替原有props.history.push
  } catch(err) {
    console.error(err)
  }
}
  • swal库调用错误
    检查是否正确安装引入了sweetalert相关依赖:
    1. 确认没有控制台报错swal is not defined
    2. 如果你使用的是sweetalert2库,调用API应为Swal.fire('YAY!', 'The operation was successfully added', 'success'),直接调用swal()会失效
  • 路由路径配置错误
    检查要跳转的目标路径是否在路由表中正确配置,比如edit组件要跳转的/operations/lists如果没有对应路由规则,会出现跳转无反应的情况。

内容的提问来源于stack exchange,提问作者Ignacio Garcia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:57:00