nathantsoi / vue-native-websocket

native websocket with vuex integration
943 stars 162 forks source link

Vue warn]: Error in created hook: "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable" #91

Open henrytom1703 opened 5 years ago

henrytom1703 commented 5 years ago
 mounted() {
      this.$socket.sendObj({
      method: "ping_server",
      params: 100,
      id: 0
    });
  }
PlainBane commented 4 years ago

Hi, this happens because VueNativeSock plugin is not ready when you are trying to send a message in mounted(). At that point it's ready state is 0, which mean that it's still connecting and can't send your message. It is caused by this code part: export ({ store }, inject) => { Vue.use(VueNativeSock, 'ws://localhost:4001', { format: 'msgpack', store, reconnection: true, reconnectionAttempts: 5, reconnectionDelay: 3000 }); };

VueNativeSock plugin gets injected after Nuxt/Vue is initialized and so it's not ready at mounted() hook. You need to load this plugin before Nuxt/Vue for it to be ready. I don't know a way to use this plugin with Nuxt and have access to the store.

pieterjandesmedt commented 4 years ago

You can have a watch on state.socket.isConnected and then send your message after the socket gets connected:

mounted() {
  this.unwatch = this.$store.watch(
    state => state.socket.isConnected,
    (newValue, oldValue) => {
      if (newValue === true && oldValue === false ) {
        this.$socket.sendObj({
          method: "ping_server",
          params: 100,
          id: 0
        });
      }
    }
  );
},
beforeDestroy() {
  this.unwatch();  // Don't forget to unwatch when the component is destroyed
},

More info in the vuex API reference.