diff --git a/stores/authStore.ts b/stores/authStore.ts index 9e5ca3d..056b599 100644 --- a/stores/authStore.ts +++ b/stores/authStore.ts @@ -33,12 +33,32 @@ export const useAuthStore = create()( user: state.user, isAuthenticated: state.isAuthenticated, }), + // 数据迁移函数:将旧格式的 userId 转换为新格式的 id + migrate: (persistedState: any, version: number) => { + console.log('[AuthStore] Migrating persisted state', { version, persistedState }); + + // 如果存在旧的 userId 字段,迁移到 id + if (persistedState?.user?.userId && !persistedState?.user?.id) { + console.log('[AuthStore] Migrating userId to id'); + persistedState.user.id = persistedState.user.userId; + delete persistedState.user.userId; + } + + return persistedState; + }, onRehydrateStorage: () => (state) => { console.log('[AuthStore] Hydration started'); if (state) { + // 额外的安全检查:确保 user 对象有 id 字段 + if (state.user && (state.user as any).userId && !state.user.id) { + console.log('[AuthStore] Post-hydration migration: userId -> id'); + state.user.id = (state.user as any).userId; + delete (state.user as any).userId; + } + state.isHydrated = true; console.log('[AuthStore] Hydration completed', { - user: state.user?.id, + userId: state.user?.id, isAuthenticated: state.isAuthenticated }); }