hejianhao
2026-04-01 67adeace91ca059aca62bef7f9c65b2e1de6a6d8
fix(websocket): 修复WebSocket连接管理和事件绑定问题

- 添加连接状态标志防止重复连接
- 修正关闭重连逻辑,仅在非手动关闭时重连
- 优化事件绑定,将多个监听器绑定提取到独立函数
- 在组件卸载时清理open事件监听器
2个文件已修改
42 ■■■■■ 已修改文件
src/robotaxi/pages/begin-route/index.tsx 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/utils/websocket.ts 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/robotaxi/pages/begin-route/index.tsx
@@ -1009,6 +1009,10 @@
        wsManager.off('order_reassign', orderReassignHandlerRef.current);
        orderReassignBound.current = false;
      }
      if (socketOpenHandlerRef.current) {
        wsManager.off('open', socketOpenHandlerRef.current);
        socketOpenHandlerRef.current = null;
      }
    };
  }, []);
@@ -1422,6 +1426,10 @@
  }, [tripStatus, vehicleLocation, vehicleDirection, vehicleMarkerId]);
  const bindSocketListeners = () => {
    if (!authSuccessBound.current && authSuccessHandlerRef.current) {
      wsManager.on('auth_success', authSuccessHandlerRef.current);
      authSuccessBound.current = true;
    }
    if (!orderStatusBound.current && orderStatusHandlerRef.current) {
      wsManager.on('order_status', orderStatusHandlerRef.current);
      orderStatusBound.current = true;
@@ -1782,22 +1790,7 @@
      return
    }
    setTripStatus(2);
    if (!authSuccessBound.current && authSuccessHandlerRef.current) {
      wsManager.on('auth_success', authSuccessHandlerRef.current);
      authSuccessBound.current = true;
    }
    if (!orderStatusBound.current && orderStatusHandlerRef.current) {
      wsManager.on('order_status', orderStatusHandlerRef.current);
      orderStatusBound.current = true;
    }
    if (!orderRouteBound.current && orderRouteHandlerRef.current) {
      wsManager.on('order_route', orderRouteHandlerRef.current);
      orderRouteBound.current = true;
    }
    if (!orderUpdatePriceBound.current && orderUpdatePriceHandlerRef.current) {
      wsManager.on('order_update_price', orderUpdatePriceHandlerRef.current);
      orderUpdatePriceBound.current = true;
    }
    bindSocketListeners();
  }, 500)
  // 确认取消
src/utils/websocket.ts
@@ -9,6 +9,8 @@
  private socketTask: Taro.SocketTask | null = null;
  private url: string = '';
  private isConnected: boolean = false;
  private isConnecting: boolean = false;
  private isManualClose: boolean = false;
  private reconnectAttempts: number = 0;
  private maxReconnectAttempts: number = 5;
  private reconnectTimer: any = null;
@@ -31,12 +33,14 @@
   * @param url WebSocket地址
   */
  public async connect(url: string) {
    if (this.socketTask || this.isConnected) {
    if (this.socketTask || this.isConnected || this.isConnecting) {
      console.log('WebSocket 已连接或正在连接中');
      return;
    }
    this.url = url;
    this.isConnecting = true;
    this.isManualClose = false;
    console.log(`正在连接 WebSocket: ${url}`);
    const uid = await getStorage(_UID) || '-1';
@@ -48,12 +52,14 @@
      success: () => { },
      fail: (err) => {
        console.error('WebSocket 连接失败:', err);
        this.isConnecting = false;
        this.handleReconnect();
      }
    });
    const maybeTask: any = task as any;
    if (maybeTask && typeof maybeTask.onOpen === 'function') {
      this.socketTask = maybeTask;
      this.isConnecting = false;
      this.initEventListeners();
      return;
    }
@@ -61,15 +67,18 @@
      maybeTask
        .then((resolvedTask) => {
          this.socketTask = resolvedTask;
          this.isConnecting = false;
          this.initEventListeners();
        })
        .catch((err) => {
          console.error('WebSocket 连接失败:', err);
          this.isConnecting = false;
          this.handleReconnect();
        });
      return;
    }
    this.socketTask = null;
    this.isConnecting = false;
    this.initEventListeners();
  }
@@ -114,7 +123,7 @@
        this.stopHeartbeat();
        this.socketTask = null;
        if (res.code !== 1000) {
        if (!this.isManualClose) {
          this.handleReconnect();
        }
        this.notifyListeners('close', res);
@@ -163,7 +172,7 @@
      this.stopHeartbeat();
      this.socketTask = null;
      if (res.code !== 1000) {
      if (!this.isManualClose) {
        this.handleReconnect();
      }
      this.notifyListeners('close', res);
@@ -208,6 +217,7 @@
   * 关闭连接
   */
  public close() {
    this.isManualClose = true;
    this.stopHeartbeat();
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
@@ -222,6 +232,7 @@
      this.socketTask = null;
    }
    this.isConnected = false;
    this.isConnecting = false;
  }
  /**