React Invalid Hook Call警告问题排查求助
React Warning: Invalid Hook Call 排查求助
我的应用中多个位置出现React Warning: Invalid Hook Call错误,所有涉及状态的页面均受影响。此前搭建过配置类似的应用,从未遇到该问题。
根据React文档,该错误的可能原因包括:
- React版本不匹配
- 重复引入React
- 钩子调用不符合规则
我已经检查过React与react-dom的版本兼容性,也确认没有重复引入React的情况,但问题依然存在。
触发错误的钩子调用示例(Login.js)
const LoginForm = (props) => { const [userFormData, setUserFormData] = useState({ username: '', password: '' }); const [validated] = useState(false); const [showAlert, setShowAlert] = useState(false); const [loginUser, { error }] = useMutation(LOGIN_USER);
补充信息
- 注释掉所有
useState调用后,页面可部分加载,不会出现全白屏的情况。 - 错误截图:

App.js中LoginForm的调用代码
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { ApolloProvider, ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; import Navbar from './components/Navbar'; import Home from './pages/Home'; import Profile from './pages/Profile'; import Explore from './pages/Explore'; import LoginForm from './components/LoginForm'; import './App.css'; const httpLink = createHttpLink({ uri: '/graphql' }); const authLink = setContext((_, { headers }) => { const token = localStorage.getItem('id_token'); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '', }, }; }); const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() }) const App = () => { return ( <ApolloProvider client={client}> <Router> <div className='app'> <Navbar /> <div className='container'> <Switch> <Route exact path='/' component={Home} /> <Route exact path='/profile' component={Profile} /> <Route exact path='/profile:username?' component={Profile} /> <Route exact path='/explore' component={Explore} /> <Route exact path='/login' component={LoginForm} /> </Switch> </div> </div> </Router> </ApolloProvider> ) } export default App;
希望有人能指明排查方向,如需更多代码我可提供,感谢帮助!
内容的提问来源于stack exchange,提问作者james182
相关产品推荐
相关产品推荐

