From bbce1de60c5b4c06d39846c2bbe58a7effd16adc Mon Sep 17 00:00:00 2001 From: kurihada Date: Mon, 15 Dec 2025 10:29:49 +0800 Subject: [PATCH] =?UTF-8?q?fix(ui):=20=E4=BC=98=E5=8C=96=20WebSocket=20?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E5=92=8C=20PWA=20meta=20=E6=A0=87=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - WebSocket onopen 检查 isClosingRef,组件卸载后自动关闭连接 - 更新 PWA meta 标签为 mobile-web-app-capable --- packages/ui/src/hooks/useChat.ts | 16 ++++++++++++++-- packages/web/index.html | 2 +- 2 files changed, 15 insertions(+), 3 deletions(-) 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 @@ - +