Skip to content

Commit d6d7789

Browse files
author
shijiashuai
committed
```
fix: 添加 localStorage 安全访问封装,避免 SSR 环境报错 新增 getSafeLocalStorage 辅助函数检测 window 对象存在性并捕获异常,在 getOrCreateSessionId 和 initSession 中使用该函数替代直接访问 localStorage,当 localStorage 不可用时降级为仅生成会话 ID 而不持久化,确保在服务端渲染或隐私模式下不会抛出异常。 ```
1 parent 6a7f0db commit d6d7789

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/store/digitalHumanStore.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,25 @@ const generateSessionId = (): string => {
7171
return `session_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
7272
};
7373

74+
const getSafeLocalStorage = (): Storage | null => {
75+
if (typeof window === 'undefined') return null;
76+
try {
77+
return window.localStorage;
78+
} catch {
79+
return null;
80+
}
81+
};
82+
7483
// 从 localStorage 获取或创建会话ID
7584
const getOrCreateSessionId = (): string => {
76-
const stored = localStorage.getItem('metahuman_session_id');
85+
const storage = getSafeLocalStorage();
86+
if (!storage) {
87+
return generateSessionId();
88+
}
89+
const stored = storage.getItem('metahuman_session_id');
7790
if (stored) return stored;
7891
const newId = generateSessionId();
79-
localStorage.setItem('metahuman_session_id', newId);
92+
storage.setItem('metahuman_session_id', newId);
8093
return newId;
8194
};
8295

@@ -123,7 +136,10 @@ export const useDigitalHumanStore = create<DigitalHumanState>((set, get) => ({
123136
// 会话管理
124137
initSession: () => {
125138
const newId = generateSessionId();
126-
localStorage.setItem('metahuman_session_id', newId);
139+
const storage = getSafeLocalStorage();
140+
if (storage) {
141+
storage.setItem('metahuman_session_id', newId);
142+
}
127143
set({ sessionId: newId, chatHistory: [] });
128144
},
129145

0 commit comments

Comments
 (0)