Vue3组合式API中watch内使用useMutation报错求助
解决Vue3组合式API中watch回调内调用useMutation的错误
问题原因
- Vue3组合式API要求所有组合式函数(比如
useQuery、useMutation)必须在组件setup的顶层同步调用,不能放在watch回调、异步函数或者循环这类延迟执行的代码块里。 - 你在
watch回调里调用useMutation时,已经脱离了组件的注入上下文,导致Apollo Client无法被找到,从而抛出"Apollo client with id default not found"的错误。
解决方案
把useMutation的调用移到组件setup的顶层,在watch回调里直接使用提前获取到的mutate方法即可。
修改后的代码
<script setup> import { useRouter, useRoute } from 'vue-router' import { useMutation, useQuery } from '@vue/apollo-composable' import { useSessionStore } from '@/stores/SessionStore' import UPDATE_NFCUSER_EMAIL_VERIFICATION_CODE from '@/graphql/UpdateNfcUserEmailVeriifcationCode.mutation.gql' import GET_NFCUSER_ID_BY_EMAIL_VERIFICATION_CODE from '@/graphql/GetNfcUserIdByEmailVerificationCode.query.gql' import { watch, ref } from 'vue' const sessionStore = useSessionStore() const router = useRouter() const route = useRoute() const route_verification_code = route.params.verification_code const code_not_verified = ref(false) // 将useQuery和useMutation都放在setup顶层 const { result } = useQuery(GET_NFCUSER_ID_BY_EMAIL_VERIFICATION_CODE, { verification_code: route_verification_code, }) const { mutate: updateEmailVerification } = useMutation(UPDATE_NFCUSER_EMAIL_VERIFICATION_CODE) watch(result, (newVal) => { if (newVal?.getNfcUserIdByEmailVerificationCode?.status === 200) { const nfc_user_id = newVal?.getNfcUserIdByEmailVerificationCode?.nfc_user_id if (nfc_user_id) { console.log('Verification Code is valid') sessionStore.setCurrentUserVerified(true) sessionStore.setCurrentNfcUserId(nfc_user_id) // 直接调用顶层声明好的mutate方法 updateEmailVerification({ nfcUserId: nfc_user_id, }) } else { console.log('Code is not correct') code_not_verified.value = true } } else { console.log('Code is not correct') code_not_verified.value = true } }) </script>
额外说明
- 所有
@vue/apollo-composable提供的组合式函数(useQuery、useMutation、useSubscription等)都必须遵守Vue组合式API的调用规则,只能在setup顶层或其他组合式函数的顶层调用。 - 如果需要在异步场景下使用mutate,只需要提前在顶层获取到
mutate方法,之后在任何地方调用它都没问题,因为它已经绑定了正确的Apollo Client上下文。
内容的提问来源于stack exchange,提问作者emmgee
相关产品推荐
相关产品推荐

