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

React Antd Notification仅在页面刷新后才显示的问题求助

Antd Notification 仅页面刷新后才显示的排查与解决

可能的原因及解决办法

1. 错误分支未正确触发

先确认你的错误捕获逻辑是否真的走到了notification.error的代码块:

  • 在catch分支开头加console.log(error),查看error.code是否确实不是"ERR_BAD_REQUEST",以及error.response是否存在。
  • 当请求出现网络错误时,error.response大概率是undefined,这时JSON.stringify(error.response.data)会直接抛出异常,导致Notification代码根本没机会执行。可以改成安全的写法:
notification.error({
    message: t("Error while saving"),
    description: error.response?.data ? JSON.stringify(error.response.data) : "Network error occurred",
    placement: "topRight",
    duration: 2,
})

2. Axios拦截器吞掉了错误

如果项目里配置了Axios全局响应拦截器,一定要确保在处理错误后重新抛出错误,否则上层的catch分支根本捕获不到异常:

axios.interceptors.response.use(
  response => response,
  error => {
    // 这里可以加一些全局错误处理逻辑
    return Promise.reject(error); // 必须调用reject,错误才会传递到组件的catch里
  }
);

3. Notification被页面元素遮挡

有时候Notification已经正常触发,但被页面中z-index更高的元素(比如弹窗、导航栏)挡住了。可以手动提高Notification的层级:

notification.error({
    message: t("Error while saving"),
    description: error.response?.data ? JSON.stringify(error.response.data) : "Network error occurred",
    placement: "topRight",
    duration: 2,
    style: { zIndex: 9999 } // 给个足够高的z-index值
})

4. 组件卸载导致Notification未执行

如果handleSave执行过程中用户跳转了页面,组件被卸载,可能导致Notification无法正常显示。这种情况可以考虑:

  • 在组件卸载前取消请求(用Axios的CancelToken)
  • 或者使用全局状态管理来触发Notification,确保不受组件生命周期影响

5. 确认Notification导入正确

检查你的导入语句,确保是从Antd官方包中导入的Notification:

import { notification } from 'antd';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:25:01