@@ -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
7584const 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