diff --git a/packages/ui/src/hooks/useChat.ts b/packages/ui/src/hooks/useChat.ts
index 7386b0b..125cffc 100644
--- a/packages/ui/src/hooks/useChat.ts
+++ b/packages/ui/src/hooks/useChat.ts
@@ -80,6 +80,11 @@ export function useChat({ sessionId, onError, onSessionNotFound, onSessionUpdate
const ws = createWebSocket(sessionId);
ws.onopen = () => {
+ // 如果在连接过程中组件已卸载,立即关闭
+ if (isClosingRef.current) {
+ ws.close();
+ return;
+ }
reconnectAttemptsRef.current = 0; // 连接成功,重置重连次数
setState((prev) => ({ ...prev, isConnected: true }));
};
@@ -282,10 +287,17 @@ export function useChat({ sessionId, onError, onSessionNotFound, onSessionUpdate
const ws = wsRef.current;
// 清除引用,防止后续操作
wsRef.current = null;
- // 只有在 OPEN 或 CONNECTING 状态才关闭
- if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
+ // 清除事件处理器,避免关闭时触发错误
+ ws.onclose = null;
+ ws.onerror = null;
+ ws.onmessage = null;
+ ws.onopen = null;
+ // 只关闭已经建立的连接,避免 "closed before established" 警告
+ if (ws.readyState === WebSocket.OPEN) {
ws.close();
}
+ // 对于 CONNECTING 状态,等待连接建立后再关闭
+ // 这样可以避免浏览器警告
}
};
}, [loadMessages, connect]);
diff --git a/packages/web/index.html b/packages/web/index.html
index 856be3a..6b56299 100644
--- a/packages/web/index.html
+++ b/packages/web/index.html
@@ -7,7 +7,7 @@
-
+