Next.js中使用Apollo Codegen生成Hook触发Invalid hook call错误求助
问题描述
我尝试使用Codegen生成的Hook实现注册mutation功能,代码如下:
export default function signUpComponent() { const { register, handleSubmit } = useForm<SignUpFormData>(); const [signUpMutation, { data, loading, error }] = useSignUpMutation(); const { setToken } = useAuth(); const onSubmit: SubmitHandler<SignUpFormData> = async (data) => { try { const result = await await signUpMutation({ variables: { input: data, }, }); if (result.errors) { throw new Error('Cannot sign up' + result.errors); } if (result.data) { setToken(result.data.signUp.token); console.log(result.data.signUp.token); } } catch (e) { throw new Error(e); } }; return ( <form onSubmit={handleSubmit(onSubmit)}> <label>First Name:</label> <input className='w-1/4' {...register('firstName', { required: true, maxLength: 20 })} /> <label>Last Name:</label> <input className='w-1/4' {...register('lastName', { required: true, pattern: /^[A-Za-z]+$/i })} /> <label>Email:</label> <input className='w-1/4' {...register('email', { required: true, pattern: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/, })} /> <label>Password:</label> <input className='w-1/4' {...register('password', { required: true, maxLength: 15 })} /> <input type='submit' /> </form> ); }
访问http://localhost:3000/signup页面时抛出如下运行时错误:
Unhandled Runtime Error Error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
已经尝试将相关逻辑包裹在useEffect、useCallback中,也试过使用异步立即执行函数(IIFE)等方案,均未解决问题。
项目仓库地址:https://github.com/Jocelyn59435/Trackky_frontend
解决方案
按优先级依次排查修改:
- 修正组件命名:React要求自定义函数组件必须首字母大写,将
signUpComponent改为SignUpComponent。小写开头的函数会被React判定为普通函数,内部调用Hook会直接违反Hook调用规则,触发报错。 - 修正代码笔误:代码中存在重复的
await关键字,将const result = await await signUpMutation改为const result = await signUpMutation。 - 检查自定义Hook合法性:确认Codegen生成的
useSignUpMutation符合自定义Hook规则,命名以use开头,内部不存在条件调用Hook的逻辑。 - 检查React版本一致性:执行
npm ls react检查本地是否存在多个版本的React依赖,如果存在多个版本,统一依赖版本即可解决冲突。 - 检查路由配置:确认路由中引用组件时是直接传递组件引用,而非执行函数后的返回值,比如不要写
component: signUpComponent(),正确写法为component: SignUpComponent。
内容的提问来源于stack exchange,提问作者Housoul
相关产品推荐
相关产品推荐

