Open2

Nuxtjs の useContext() で、This must be called within a setup function. のエラーが出る

Ryosuke MiyamotoRyosuke Miyamoto

これは useContext は呼べて、問題なし(エラー起きない)

pages/hoge.vue
<script>
// 略
setup(){
    const res = useAsync(async () => {
      const { $axios } = useContext()
      const data = await $axios.$get<Responce>(`/api`)
     }
}
</script>

これも useContext は呼べて、問題なし(エラー起きない)

compositions/api.ts
export const fetchApi = async ():Responce => {
      const { $axios } = useContext()
      const data = await $axios.$get<Responce>(`/api`)
}
pages/hoge.vue
<script>
import { fetchApi } from "~/compositions/api"
// 略
setup(){
    const res = useAsync(async () => {
      const { $axios } = useContext()
      const data = await fetchApi()
     }
}
</script>

この2回目以降に useContext() が含まれる関数を呼ぶと useContext の上記エラーになる。謎

pages/hoge.vue
<script>
import { fetchApi } from "~/compositions/api"
// 略

setup(){
    const res = useAsync(async () => {
      const { $axios } = useContext()
      const data = await fetchApi()
      const data2 = await fetchApi()
     }
}
</script>