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

登录时触发429请求过多错误及token校验路由跳转异常排查

问题分析与解决方案

核心问题

  1. 无限请求循环触发429错误:useEffect的依赖项是tokenCheck函数,但该函数未被缓存,组件每次渲染都会重新创建tokenCheck,导致useEffect无限重复执行,反复调用mainApi.getContent发送请求,最终触发服务端限流。
  2. 路由跳转逻辑冗余:tokenCheck中的history.push('/movies')与路由中的Redirect逻辑叠加,可能加重跳转循环。

修复步骤

1. 缓存tokenCheck函数,终止无限循环

使用React.useCallback包裹tokenCheck,确保函数仅在依赖项变化时重新创建,避免useEffect无意义触发:

const [loggedIn, setLoggedIn] = React.useState(false);

// 用useCallback缓存函数,仅依赖必要变量
const tokenCheck = React.useCallback(() => {
    const jwt = localStorage.getItem('jwt');
    if (!jwt) return;

    mainApi.getContent(jwt)
        .then((res) => {
            // 仅当前未登录时更新状态并跳转,避免重复操作
            if (res && !loggedIn) {
                setLoggedIn(true);
                history.push('/movies');
            }
        })
        .catch((err) => {
            setIsOpenPopup(true);
            setPopupTitle('error tokenCheck');
        });
}, [loggedIn, history, mainApi, setIsOpenPopup, setPopupTitle]);

React.useEffect(() => {
    tokenCheck();
}, [tokenCheck]);

2. 简化逻辑(可选)

直接将tokenCheck的逻辑移入useEffect,彻底避免函数依赖问题:

const [loggedIn, setLoggedIn] = React.useState(false);

React.useEffect(() => {
    const jwt = localStorage.getItem('jwt');
    if (!jwt) return;

    mainApi.getContent(jwt)
        .then((res) => {
            if (res && !loggedIn) {
                setLoggedIn(true);
                history.push('/movies');
            }
        })
        .catch((err) => {
            setIsOpenPopup(true);
            setPopupTitle('error tokenCheck');
        });
}, [loggedIn, history, mainApi, setIsOpenPopup, setPopupTitle]);

3. 确保ProtectedRoute逻辑正确

自定义的ProtectedRoute需准确判断登录状态,避免跳转冲突:

const ProtectedRoute = ({ children, path }) => {
    return (
        <Route path={path}>
            {loggedIn ? children : <Redirect to="/signin" />}
        </Route>
    );
};

4. 完善响应处理函数

确认MainApi中的_returnResult正确处理HTTP响应,避免无效token被误判:

_returnResult = (res) => {
    if (res.ok) {
        return res.json();
    }
    return Promise.reject(`请求失败:${res.status}`);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:30:51