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

如何阻止MERN栈电商项目中React页面展示请求失败的状态码报错

问题根因

你遇到的错误展示问题核心是前端的异步请求错误没有被正确捕获,具体有两个问题:

  1. 你混用了try/catch和.then()异步语法,且没有给createCategories异步方法添加await关键字,导致请求抛出的错误没有被当前catch块捕获,成为未处理的Promise拒绝,触发了全局错误提示。
  2. 错误场景下也没有重置loading状态,可能会导致页面持续处于加载中。

修复方案

1. 前端代码调整

你可以二选一任选一种写法:

写法一:统一使用async/await语法(更推荐)

const handleSubmit = async(e) => {
    e.preventDefault();
    setLoading(true)
    try{
        // 新增await等待异步请求执行完成
        const res = await createCategories(category, localStorage.getItem('token'))
        console.log(res)
        setLoading(false)
        setCompleted(true)
        setCreateCategory(res.data)
    }catch(err){
        // 错误场景也要关闭loading
        setLoading(false)
        setError(true)
        // 新增可选链判断,避免网络无响应时err.response为undefined报错
        setErrorMsg({
            "msg": err.response?.data || "请求发送失败,请检查网络连接"
        })
    }
}

写法二:保持.then()语法,追加.catch捕获错误

const handleSubmit = (e) => {
    e.preventDefault();
    setLoading(true)
    createCategories(category, localStorage.getItem('token'))
    .then(res => {
        console.log(res)
        setLoading(false)
        setCompleted(true)
        setCreateCategory(res.data)
    })
    // 新增catch块捕获异步错误
    .catch(err => {
        setLoading(false)
        setError(true)
        setErrorMsg({
            "msg": err.response?.data || "请求发送失败,请检查网络连接"
        })
    });
}

2. 后端代码优化(可选,方便后续统一处理错误格式)

建议将错误返回的纯文本改为JSON格式,和成功返回的格式保持一致,避免前端解析错误:

try{
    const {name} = req.body;
    const category = await new Category({ name, slug: slugify(name)}).save();
    res.json({'msg': "Category Created"})
}catch(err){
    console.log(err)
    // 把send改为json返回
    res.status(400).json({"msg": "Create Category Failed..."})
}

额外优化建议

可以给axios添加全局响应拦截器,统一处理公共错误(比如401无权限跳登录页),同时避免单个请求漏写错误捕获导致全局报错:

// 在你初始化axios的配置文件中添加
import axios from 'axios'

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    // 全局公共错误处理示例
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    // 必须返回错误,否则业务代码的catch块无法接收到错误信息
    return Promise.reject(error)
  }
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 09:54:03