为什么 vuex4.0 不能作为 Vue3 onMounted 异步函数中的钩子

Why vuex4.0 not work as hooks inside Vue3 onMounted async function

bar1(),bar2(),bar3()是三个分开的情况,我想选择其中一个作为foo()完成时真正的bar(),然后发送到web socket,然后由vuex存储回调值。

1.bar1(): 我发现如果我将任何 bar1() 放入 onMounted 范围,它就无法工作,store turn 未定义。

2.bar2():我将 XXX.vue 中的参数“store”传递给 bar2(),它起作用了。

3.bar3(): 奇怪的是,如果 bar3() 不在 onMounted 范围内,它可以工作,虽然这不是异步函数,无需等待 foo(),这不是我期望的方式。

msg_state 在 store.state... 中存储一些东西,我想提交它来更新它的值

问题:

  1. bar1(),bar2(),bar3()有什么区别
  2. 为什么 bar2() as bar() 可以工作,而 bar1() as bar() 不能工作?
  3. 这是因为 bar3() 在 setup() 范围内而不是 onMounted() 范围内?
// In socket.js
// not work
import { useStore } from 'vuex'
export const bar1 = async(input) =>  {
// store is undefined
const store = useStore()
socket = io(url)
    socket.on('message', (msg)  = {
        // commit is not defined
        store.commit("msg_state", msg) 
    })
}

// work
export const bar2 = async(input, store) =>  {
    socket = io(url)
    socket.on('message', (msg)  = {
        store.commit("msg_state", msg) 
    })
}

// work but not async
import { useStore } from 'vuex'
export const bar3 = (input) =>  {
const store = useStore()
    socket = io(url)
    socket.on('message', (msg)  = {
        store.commit("msg_state", msg) 
    })
}

//In XXX.vue
import bar from '@/util/socket.js'
...
export default {
    setup() {
        const xxx = reactive({input: oldVal})
        const store = useStore()
        onMounted(async () => {
        //{input: oldVal}
        await foo()
        //{input: newVal}

        // option1: bar1 as bar
        await bar1(xxx.input) // counldn't work

        // option2: bar2 as bar
        await bar2(xxx.input, store) // this could work

        })
        // option3: bar3 as bar
        bar3(xxx.input) // this could work but not async
    }
}

bar1bar3 也是错误的,因为钩子通常应该在 setup 中调用。 bar2 不需要访问整个商店。

创建函数 async 是语义错误,因为它们是异步的但不涉及承诺。而且,还有message订阅,不能翻译成promises,除非是一次性事件。

如果是一次性的,commit 在操作外部使用意味着特定于商店的业务逻辑分散在应用程序中。整个 bar 可能是 Vuex 动作:

const bar = async ({ commit,  state }, input ) =>  {
  // socket is likely a part of state
  await new Promise(resolve => {
    socket.once('message', (msg) => {
      commit("msg_state", msg) 
      resolve(msg);
    });
  })
}