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

React useEffect在MobX Store更新前执行导致错误跳转求助

问题解决:避免React+MobX授权校验时的错误跳转

问题根源

你的跳转逻辑useEffect仅在组件挂载时执行一次,此时异步的checkAuth请求尚未完成,store.isAuth还是初始值false,导致页面错误跳转到登录页;后续checkAuth完成后isAuth变为true时,该useEffect因无对应依赖不会重新执行,无法纠正跳转行为。

具体修改方案

1. 修复授权跳转逻辑

修改App.js中负责跳转的useEffect,将store.isAuth和store.isLoading加入依赖数组,确保状态变化时重新执行判断,且仅在加载完成后进行跳转:

useEffect(() => {
    // 加载完成后,若未授权则跳转登录页
    if (!store.isLoading && !store.isAuth) {
        console.log('NAVIGATE TO /login');
        navigate('/login');
    }
}, [store.isAuth, store.isLoading, navigate]) 

2. 优化订单请求时机

checkOrdersInWork需要用户授权后才能正常发起请求,因此修改对应的useEffect,仅在用户已授权时执行:

useEffect(() => {
    if (store.isAuth) {
        store.checkOrdersInWork();
    }
}, [store.isAuth]);

3. 完整修改后的App.js

import React, { useContext, useEffect } from 'react';
import { Context } from "./index";
import { observer } from "mobx-react-lite";
import { useNavigate } from 'react-router-dom';
import AppRouter from './components/AppRouter';

const App = () => {
    const { store } = useContext(Context);
    const navigate = useNavigate();

    useEffect(() => {
        console.log(process.env.REACT_APP_API_URL)
        if (localStorage.getItem('token')) {
            store.checkAuth();
        }
    }, []);

    // 仅当用户授权后获取进行中的订单
    useEffect(() => {
        if (store.isAuth) {
            store.checkOrdersInWork();
        }
    }, [store.isAuth]);
    
    // 加载完成后判断是否跳转登录
    useEffect(() => {
        if (!store.isLoading && !store.isAuth) {
            console.log('NAVIGATE TO /login');
            navigate('/login');
        }
    }, [store.isAuth, store.isLoading, navigate]) 

    if (store.isLoading) {
        return <div>Загрузка...</div>
    }

    return (
        <div>
            <AppRouter/>
        </div>
    );
};

export default observer(App);

逻辑说明

  • 当本地存在token时,checkAuth发起异步请求,此时isLoading变为true,组件显示加载状态,不会执行跳转逻辑;
  • checkAuth请求完成后,isLoading变为false,isAuth根据校验结果更新:
    • 校验成功(isAuth=true):不跳转,同时触发订单数据请求;
    • 校验失败(isAuth=false):跳转到登录页;
  • 若本地无token,checkAuth不执行,isLoading保持false、isAuth为false,直接跳转登录页,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:45:11