You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React集成Google OAuth2遇useState读取null错误求助

React中Google OAuth2实现报错:Cannot read properties of null (reading 'useState')

问题详情

我是React新手,首次尝试实现Google OAuth2功能,当前代码如下:

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from "react-router-dom";

import App from './App';
import './index.css';
import {GoogleOAuthProvider} from "@react-oauth/google";

ReactDOM.render(
    <Router>
        <GoogleOAuthProvider
            clientId="456606812667-thitf7kr69bukm71bmecv5******.apps.googleusercontent.com">
                <App />
        </GoogleOAuthProvider>
    </Router>,

    document.getElementById('root'));

运行时触发以下错误:

Cannot read properties of null (reading 'useState')
TypeError: Cannot read properties of null (reading 'useState')
    at useState (http://localhost:3000/static/js/bundle.js:48755:25)
    at useLoadGsiScript (http://localhost:3000/static/js/bundle.js:47023:114)
    at GoogleOAuthProvider (http://localhost:3000/static/js/bundle.js:47060:36)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:25305:22)
    at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:28591:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:29887:20)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:14897:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:14941:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:14998:35)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:34872:11)

怀疑是ClientID错误,但不知道如何验证,求解决办法。

解决步骤

1. 排查React版本兼容性

这个报错大概率是React版本与@react-oauth/google不匹配导致的,该库要求React版本≥16.8(支持Hook):

  • 项目根目录执行npm list react,确认版本符合要求;
  • 版本过低的话,执行npm install react@latest react-dom@latest升级。

2. 验证ClientID有效性

  • 打开Google Cloud控制台,找到对应项目,进入「API和服务」→「凭据」;
  • 找到已创建的「OAuth 2.0客户端ID」,核对是否和代码中的完全一致(别漏了末尾的.apps.googleusercontent.com);
  • 确保创建的是「Web应用」类型的客户端ID,不是Android/iOS等其他类型。

3. 检查依赖安装与导入

  • 执行npm uninstall @react-oauth/google && npm install @react-oauth/google,重新安装依赖;
  • 确认{GoogleOAuthProvider}拼写正确,导入语句使用英文双引号。

4. 调整组件嵌套顺序

尝试把GoogleOAuthProvider放在Router外层,确保Provider优先渲染:

ReactDOM.render(
    <GoogleOAuthProvider clientId="你的ClientID">
        <Router>
            <App />
        </Router>
    </GoogleOAuthProvider>,
    document.getElementById('root')
);

5. 清除缓存重启项目

  • 执行npm cache clean --force清除npm缓存;
  • 重启开发服务器npm start。

内容的提问来源于stack exchange,提问作者Tim Kiryachek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:20:39