Vue 3-inject() 只能在设置或功能组件内部使用

Mar*_*tin 19 javascript vue.js vuex vuejs3 vue-composition-api

我不明白为什么我会收到此错误。我试图在组合函数中使用 Vuex 存储,但它不断向我抛出有关注入的错误(我什至没有使用注入)。我的应用程序对后端进行等待 api 调用,如果出现错误,则调用我的组合函数。

[Vue warn]: inject() can only be used inside setup() or functional components.
inject    @ runtime-dom.esm-bundler-9db29fbd.js:6611
useStore  @ vuex.esm-bundler.js:13
useErrorHandling @  useErrorHandling.js:5
checkUserExists  @  auth.js:53
Run Code Online (Sandbox Code Playgroud)

这是我的合成函数

import { useStore } from 'vuex'

function useErrorHandling()
{
    const store = useStore()  // <-- this line

    function showError(errorMessage) {
        console.log(errorMessage)
    }

    return { showError }
}

export default useErrorHandling
Run Code Online (Sandbox Code Playgroud)

如果我删除这一行,那么它就不会抛出该错误

// const store = useStore()  // <-- this line
Run Code Online (Sandbox Code Playgroud)

更新:这就是函数的调用方式。

/**
     * Check if a user exists in database
     */
    static async checkUserExists(data)
    {
        const { env } = useEnv()
        const { jsonHeaders } = useHTTP()
        const { showError } = useErrorHandling()
        
        try {
            let response = await fetch(`${env('VITE_SERVER_URL')}/auth/check-user-exists`, {
                method: 'POST',
                body: JSON.stringify(data),
                headers: jsonHeaders,
            })

            if (!response.ok) {
                let errorMessage = {
                    statusText: response.statusText,
                    statusCode: response.status,
                    body: '',
                    url: response.url,
                    clientAPI: 'api/auth.js @ checkUserExists',
                }
                
                const text = await response.text()
                errorMessage.body = text

                showError(errorMessage) // <-- here
                return
            }

            response =  await response.json()
            return response.user_exists
        } catch (error) {
            alert('Error occured!')
            console.log(error)
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 23

该错误告诉您这useStore仅适用于组件内部,因为该模块不是组件。来自文档

要访问 setup hook 中的 store,您可以调用 useStore 函数。这相当于使用 Option API 在组件内检索 this.$store。

store要在模块中使用,您可以import { store }从创建它的模块中:

商店.js

export const store = createStore({
...
})
Run Code Online (Sandbox Code Playgroud)

其他模块

import { store } from './store'
Run Code Online (Sandbox Code Playgroud)