From fba4541fa5bf5780cd1137938582c136a9e8e655 Mon Sep 17 00:00:00 2001 From: yoge Date: Mon, 9 Mar 2026 21:46:26 +0800 Subject: [PATCH] fix: user info api repeat call --- src/contexts/AuthContext.tsx | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/contexts/AuthContext.tsx b/src/contexts/AuthContext.tsx index 281acc1..491efff 100644 --- a/src/contexts/AuthContext.tsx +++ b/src/contexts/AuthContext.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useMemo, ReactNode, useCallback, useEffect, useReducer } from 'react'; +import { createContext, useContext, useMemo, ReactNode, useCallback, useEffect, useReducer, useRef } from 'react'; import { authService } from '../lib/authService'; import { ApiErrorMessages } from '../types/api'; import type { GoogleOAuthCallbackRequest, UserInfo } from '../types/api'; @@ -147,20 +147,25 @@ export function AuthProvider({ children }: { children: ReactNode }) { dispatch({ type: 'SIGN_OUT' }); }, []); + const syncedTokenRef = useRef(null); + useEffect(() => { + const currentUser = state.user; + const currentToken = state.token; + + if (!currentUser || !currentToken) { + return; + } + + // 已经为当前 token 同步过,跳过(防止 StrictMode 双调用或 effect 重复执行) + if (syncedTokenRef.current === currentToken) { + return; + } + + syncedTokenRef.current = currentToken; let cancelled = false; - let hasSynced = false; const syncUserProfile = async () => { - const currentUser = state.user; - const currentToken = state.token; - - if (!currentUser || !currentToken || hasSynced) { - return; - } - - hasSynced = true; - try { const profile = await authService.getUserInfo(); if (cancelled) { @@ -175,6 +180,10 @@ export function AuthProvider({ children }: { children: ReactNode }) { }); } catch { // Keep token-derived identity if profile sync fails. + if (!cancelled) { + // 请求失败时重置,允许下次挂载时重试 + syncedTokenRef.current = null; + } } };