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

Next.js中Axios拦截器返回401错误引发未处理运行时异常问题

解决Next.js中Axios 401错误未处理的问题

问题根源

  1. 登录Action中**未使用await**调用Axios请求,导致Promise拒绝时无法被try/catch捕获,错误直接冒泡为全局未处理运行时错误
  2. Axios响应拦截器直接Promise.reject(error),若业务代码未显式处理错误,会触发Next.js的全局错误提示

解决方案

1. 修复登录Action的异步处理逻辑

给axios.post添加await,确保请求错误能被try/catch捕获:

import axios from "../../api/axios";
import { authConstants } from "../types";

export const login = (data) => {
  return async (dispatch) => {
    try {
      dispatch({
        type: authConstants.LOGIN_REQUEST,
      });
      // 加上await等待请求完成,确保错误能进入catch块
      const res = await axios.post("/user/login", data);
      if (res.status === 200) {
        dispatch({
          type: authConstants.LOGIN_SUCCESS,
          payload: res.data,
        });
      }
    } catch (error) {
      console.log(error, authConstants);
      dispatch({
        type: authConstants.LOGIN_FAILURE,
        payload: { error: error.response?.data?.error || "登录失败" },
      });
    }
  };
};

2. 优化Axios响应拦截器,统一处理401错误

在拦截器中针对401状态码做统一处理(清除token、跳转登录页),同时可根据业务需求决定是否继续抛出错误:

import axios from "axios";
import store from "../redux/store";
import getConfig from 'next/config';
import { authConstants } from "../redux/types";

const { publicRuntimeConfig } = getConfig();

let token = "";
if (typeof window !== 'undefined') {
  const item = localStorage.getItem('key')
  token = item;
}
const axiosInstance = axios.create({
  baseURL: publicRuntimeConfig.backendURL,
  headers: {
    Authorization: token ? `Bearer ${token}` : "",
  },
});

axiosInstance.interceptors.request.use(
  function (config) {
    const { auth } = store.getState();
    if (auth.token) {
      config.headers.Authorization = `Bearer ${auth.token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (res) => {
    console.log(res)
    return res;
  },
  (error) => {
    console.log(error)
    // 针对401未授权错误做统一处理
    if (error.response?.status === 401) {
      // 清除本地存储的token
      if (typeof window !== 'undefined') {
        localStorage.removeItem('key');
      }
      // 更新Redux状态为未登录
      store.dispatch({ type: authConstants.LOGOUT });
      // 跳转到登录页
      if (typeof window !== 'undefined') {
        window.location.href = '/login';
      }
      // 若不需要业务代码再处理,可返回resolve终止错误冒泡
      // return Promise.resolve();
    }
    // 其他错误继续抛出,交由业务代码的catch处理
    return Promise.reject(error);
  }
);

export default axiosInstance;

3. 确保所有Axios请求都显式处理错误

在组件中调用请求时,务必通过try/catch或.catch()处理错误,避免未处理的Promise拒绝:

// 示例组件中调用登录逻辑
const handleLogin = async (formData) => {
  try {
    await dispatch(login(formData));
  } catch (error) {
    // 处理额外的错误提示逻辑
    console.error("登录失败:", error);
  }
};

内容的提问来源于stack exchange,提问作者Ashikur Rahman Munna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:54:20