React共享项目状态更新函数触发Invalid hook call错误,如何修复?
修复React Invalid Hook Call错误的两种方案
你的错误核心是React Hook只能在函数组件的顶层或者自定义Hook的顶层调用——你现在在普通async函数里嵌套了useEffect,还在useEffect回调里调用useUpProSecStatus、useContext这些Hook,完全违反了Hook的调用规则。下面给你两种可行的修改方案:
方案一:封装成自定义Hook(推荐)
自定义Hook必须以use开头,React会识别这种命名并允许内部调用其他Hook。把你的逻辑改成这样:
export function useUpdateStatus() { // 直接在Hook顶层调用其他Hook,符合规则 const { updateProSecStatus } = useUpProSecStatus(); const { setAlertMsg } = useContext(AlertMsgContext); // 定义实际的更新函数 const updateStatus = async (sectionId: number, statusId: number) => { const res = await updateProSecStatus({ projectSectionid: sectionId, statusId: statusId, }); if (res.errors) { setAlertMsg({ message: 'Error: Failed to update status', variant: 'error', }); } }; return updateStatus; }
在组件里使用这个Hook:
function MyComponent() { // 在组件顶层调用自定义Hook const updateStatus = useUpdateStatus(); const handleUpdate = () => { // 调用拿到的更新函数 updateStatus(123, 456); }; return <button onClick={handleUpdate}>更新状态</button>; }
方案二:把Hook依赖作为参数传入
如果不想封装成Hook,可以把需要的updateProSecStatus和setAlertMsg从外部传入,让函数变成纯工具函数:
// 这里建议把any替换成你项目中对应的实际类型 export async function updateStatus( sectionId: number, statusId: number, updateProSecStatus: any, setAlertMsg: (msg: { message: string; variant: string }) => void ) { const res = await updateProSecStatus({ projectSectionid: sectionId, statusId: statusId, }); if (res.errors) { setAlertMsg({ message: 'Error: Failed to update status', variant: 'error', }); } }
在组件里使用时,先获取Hook返回值再传入:
function MyComponent() { const { updateProSecStatus } = useUpProSecStatus(); const { setAlertMsg } = useContext(AlertMsgContext); const handleUpdate = () => { updateStatus(123, 456, updateProSecStatus, setAlertMsg); }; return <button onClick={handleUpdate}>更新状态</button>; }
另外提一句:你原来代码里的fetchData;只是引用了函数,没有实际调用,应该改成fetchData();,不过这不是Hook错误的原因,但也是需要修正的细节。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

