From 00541fcf71f9a272f1def3f370f581bd79503449 Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Mon, 18 May 2026 13:27:29 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=99=BB=E5=BD=95=E8=BF=87?= =?UTF-8?q?=E5=8E=BB=E5=90=8E=20=E4=BC=9A=E8=B7=B3=E8=BD=AC=E4=B8=A4?= =?UTF-8?q?=E6=AC=A1=E7=99=BB=E5=BD=95=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/request.ts | 56 ++++++++++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/src/api/request.ts b/src/api/request.ts index 466a698..e72d62d 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -1,9 +1,11 @@ import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios'; import envConfig from '../../env'; import Cookies from 'js-cookie'; -import { message } from 'antd'; +import utils from '../lib/utils'; const API_BASE_URL = envConfig.baseURL; +const message = utils.message; // 使用全局 message + const api = axios.create({ baseURL: API_BASE_URL, @@ -28,20 +30,35 @@ api.interceptors.request.use( } ); -// 统一登出跳转方法 -const handleLogoutAndRedirect = () => { - localStorage.clear(); - Cookies.remove('userId'); - Cookies.remove('Admin-Token'); +// 🔥 全局唯一锁:保证并发多个 401 也只执行一次 +let isLoggingOut = false; - // 动态导入避免循环依赖 - import('../store').then(store => { +const handleLogoutAndRedirect = () => { + // 已经在登出流程中,直接阻止 + if (isLoggingOut) return; + + // 立即上锁 + isLoggingOut = true; + + // 清除登录信息 + try { + localStorage.clear(); + Cookies.remove('userId'); + Cookies.remove('Admin-Token'); + Cookies.remove('token'); + } catch { } + + // redux 登出 + import('../store').then(storeModule => { import('../store/userSlice').then(({ logout }) => { - store.default.dispatch(logout()); + storeModule.default.dispatch(logout()); }); }); + // 只提示一次 message.error('登录已过期,请重新登录'); + + // 只跳转一次 setTimeout(() => { window.location.href = '/login'; }, 800); @@ -51,28 +68,23 @@ const handleLogoutAndRedirect = () => { api.interceptors.response.use( (response: AxiosResponse) => { const data = response.data; - - // ============================================== - // 👇 重点:如果接口返回 code = 401,直接跳转登录 - // ============================================== - if (data?.code == 401) { + // 业务 401 → 统一走登出 + if (data?.code === 401) { handleLogoutAndRedirect(); return Promise.reject(new Error('登录已过期')); } - return data; }, - async (error: AxiosError) => { - // 网络异常 / 服务器挂了 - if (!error.response) { - message.error('服务异常或网络断开,即将重新登录'); + (error: AxiosError) => { + // HTTP 401 → 统一走登出 + if (error.response?.status == 401) { handleLogoutAndRedirect(); return Promise.reject(error); } - // HTTP 401 - if (error.response.status === 401) { - handleLogoutAndRedirect(); + // 网络异常 + if (!error.response) { + message.error('网络异常,请稍后重试'); return Promise.reject(error); }