🐛 fix(im): 主动断开 WS 后不再自动重连,同步复位 isConnected

disconnect() 之前调用 socket.close() 是异步触发 onclose,回调里会
无条件走 reconnect,导致离开 IM 主壳后 3 秒又会在后台重新打开 WebSocket。
修复:
- close 前先解绑 onclose / onerror handler,主动关闭路径不再走自动重连
- onclose 已被解绑后没人帮我们设 isConnected=false,disconnect 内手动复位,
  避免 socket=null 但 isConnected=true 的状态不一致
im
YunaiV 2026-04-26 23:08:23 +08:00
parent 1e02a40ec4
commit 8a7991261f
1 changed files with 9 additions and 1 deletions

View File

@ -544,9 +544,15 @@ export const useImWebSocketStore = defineStore('imWebSocketStore', {
/** 主动断开(切换用户 / 退出登录时用):关 socket + 停心跳 + 取消待重连 */
disconnect() {
if (this.socket) {
// close() 异步触发 onclose / onerror回调里会无条件 reconnect
// 主动关闭路径必须先解绑这两个 handler否则 3 秒后会自动连回去
this.socket.onclose = null
this.socket.onerror = null
this.socket.close()
this.socket = null
}
// onclose 已被解绑,不会再帮我们设 isConnected=false这里手动复位
this.isConnected = false
this.stopHeartbeat()
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer)
@ -557,7 +563,9 @@ export const useImWebSocketStore = defineStore('imWebSocketStore', {
/** 自动重连3 秒后再试onclose / onerror 都会进来,靠 reconnectTimer 自身防重) */
reconnect() {
this.stopHeartbeat()
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer)
}
this.reconnectTimer = setTimeout(() => {
console.log('[IM WS] reconnecting...')
this.connect()