3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue 3.x [Vue warn]: inject() can only be used inside setup() or functional components.の解消法

Last updated at Posted at 2021-01-12

発生する問題

async setup関数(正確にはPromiseを返すsetup関数)内でinjectを使用すると下記のエラーに遭遇することがあります。

import { defineComponent, inject } from 'vue'
import axios from 'axios'
import { key } from '@/store/user'

export default defineComponent({
  async setup () {
    const { data } = await axios.get('http://example.com')
    const userStore = inject(key)

    if (!userStore) {
      throw new Error(`${key} is not provided`)
    }

    return {
      userStore
    }
  }
})
[Vue warn]: inject() can only be used inside setup() or functional components.

解決策

injectを呼び出す箇所を、awaitより前にするとエラーが発生しなくなります。

import { defineComponent, inject } from 'vue'
import axios from 'axios'
import { key } from '@/store/user'

export default defineComponent({
  async setup () {
    const userStore = inject(key)

    if (!userStore) {
      throw new Error(`${key} is not provided`)
    }

    const { data } = await axios.get('http://example.com')

    return {
      userStore
    }
  }
})

Vue Router・Vuexを呼び出す際にも注意

useRoute()useRouter()またはuseStore()は内部でinjectを使用しているので、同じ問題に遭遇します。

import { defineComponent } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

export default defineComponent({
  async setup () {
    const { data } = await axios.get('http://example.com')
    const router = useRouter
  }
})

こちらも同様に呼び出し順を変更すればOKです。

import { defineComponent } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

export default defineComponent({
  async setup () {
    const router = useRouter
    const { data } = await axios.get('http://example.com')
  }
})
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?