fix: user info api repeat call

This commit is contained in:
2026-03-09 21:46:26 +08:00
parent a797b2b0d7
commit fba4541fa5

View File

@@ -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<string | null>(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;
}
}
};