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

Firebase Google认证出现Cannot read properties of undefined错误求助

问题排查与修复方案

核心错误原因

你遇到的TypeError: Cannot read properties of undefined (reading 'constructor')是因为Firebase v9版本的signInWithPopup调用参数错误,该方法需要传入两个参数:auth实例和Google认证提供者对象,而你只传入了provider。

其他待修复问题

除核心错误外,代码还有几处问题需要修正:

  • 未导入useAuthState钩子:该钩子来自react-firebase-hooks/auth,而非默认React包。
  • 无限递归渲染:Home组件中用户已登录时渲染自身<Home />,会导致组件无限嵌套调用。
  • 缺失firebaseConfig:需要补充你的Firebase项目配置信息。

修复后的完整代码

import React from "react";
import { initializeApp } from "firebase/app";
import { getAuth , GoogleAuthProvider , signInWithPopup } from "firebase/auth"
import { useAuthState } from "react-firebase-hooks/auth"; // 补充导入

// 替换为你的Firebase项目实际配置
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

function Home() {
    const [user] = useAuthState(auth);
    return (
        <div className="App">
            <header>Welcome to PixShare</header>
            <h1>Home</h1>
            <section>
                {/* 替换为实际已登录内容,避免递归 */}
                {user ? <p>欢迎回来,{user.displayName}!</p> : <SignIn />}
            </section>
        </div>
    );
}

const SignIn = () => {
    const signInWithGoogle = async () => {
        const provider = new GoogleAuthProvider();
        // 修正signInWithPopup参数,传入auth实例和provider
        try {
            await signInWithPopup(auth, provider);
        } catch (error) {
            console.error("登录失败:", error);
        }
    }

    return (
        <button onClick={signInWithGoogle}>
            Sign In With Google
        </button>
    );
};

export default Home;

关键修复点说明

  • 修正signInWithPopup调用:改为signInWithPopup(auth, provider),传入auth实例和provider对象。
  • 添加错误捕获:用try/catch包裹异步登录逻辑,便于排查后续可能出现的登录错误。
  • 修复无限递归:将登录后的<Home />替换为实际用户内容,比如欢迎信息。
  • 补充配置与导入:添加firebaseConfig和useAuthState的导入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:54:18