You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TS项目使用WebSocket遇Vuex store注入失败问题求助

问题解决:injection "store" is not found

核心原因

你遇到的错误是因为Vuex Store没有挂载到Vue应用实例上,组件内通过useStore()无法找到对应的注入实例。

解决步骤

1. 在入口文件挂载Store

找到你的项目入口文件(通常是src/main.ts),确保将创建好的Store挂载到Vue应用上:

import { createApp } from 'vue'
import App from './App.vue'
import store from './store' // 导入你的Store文件

const app = createApp(App)
app.use(store) // 关键:将Store注入到整个应用
app.mount('#app')

2. 修复Store内的WebSocket相关问题

你的Store代码存在几个潜在问题,建议同步修正:

  • 初始state不要直接实例化WebSocket,避免提前建立连接
  • 错误覆盖了WebSocket原生close方法,应改为监听onclose事件
  • 心跳定时器需存到state中,避免重复创建或无法清除

修改后的store/index.ts示例:

import { createStore } from 'vuex'
import { stateInt } from '../type/storeInterface'

const state: stateInt = {
  data: {},
  webSocket: null, // 初始化为null,避免提前连接
  heartbeatTimer: null // 存储心跳定时器
}

export default createStore({
  state,
  mutations: {
    initWebsocket(state) {
      // 先清理已有连接和定时器
      if (state.webSocket) {
        state.webSocket.close()
        state.webSocket = null
      }
      if (state.heartbeatTimer) {
        clearInterval(state.heartbeatTimer)
        state.heartbeatTimer = null
      }

      state.webSocket = new WebSocket('ws://10.253.32.125:19782')
      
      state.webSocket.onopen = () => {
        console.log('通讯开始')
        // 启动心跳,仅在连接打开时发送
        state.heartbeatTimer = setInterval(() => {
          if (state.webSocket?.readyState === WebSocket.OPEN) {
            state.webSocket.send('1')
          }
        }, 1000 * 60)
      }
      
      state.webSocket.onmessage = (e) => {
        console.log('收到的数据:', e.data)
        try {
          const data = JSON.parse(e.data)
          state.data = data // 存储解析后的JSON数据
          console.log(data)
        } catch (err) {
          console.error('数据解析失败:', err)
        }
      }
      
      state.webSocket.onerror = () => {
        console.log('通讯异常')
      }
      
      // 修正为监听onclose事件,而非覆盖close方法
      state.webSocket.onclose = () => {
        console.log('连接已断开')
        if (state.heartbeatTimer) {
          clearInterval(state.heartbeatTimer)
          state.heartbeatTimer = null
        }
      }
    },
    // 新增关闭连接的mutation,方便组件调用
    closeWebsocket(state) {
      if (state.webSocket) {
        state.webSocket.close()
        state.webSocket = null
      }
      if (state.heartbeatTimer) {
        clearInterval(state.heartbeatTimer)
        state.heartbeatTimer = null
      }
    }
  },
})

3. 组件代码优化(可选)

组件内可增加简单判断,避免极端情况下的报错:

<script lang="ts" setup>
import { onBeforeMount } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
const initSocket = () => {
  store?.commit('initWebsocket')
}

onBeforeMount(() => {
  initSocket()
})
</script>

内容的提问来源于stack exchange,提问作者ccr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:35:22