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

使用NextJS开发Firebase认证类时遇TypeError问题求助

解决Firebase认证类的TypeError错误

错误原因

你的代码存在两个核心问题:

  1. 静态方法错误访问实例属性:静态方法currentUser()里用this.auth,但静态方法的this指向Auth类本身,而非类的实例。类本身没有auth属性,导致this.auth为undefined,触发can't access property "constructor", object is undefined错误。
  2. 单例实例的属性访问逻辑错误:虽然你用了单例模式(static instance = new Auth()),但静态方法没有通过这个单例实例去访问auth属性。

修正步骤

  1. 调整静态方法currentUser():通过类的单例实例instance访问auth属性,而非直接用类本身的this。
  2. 验证Google认证提供者初始化:确保./providers中的google是正确创建的GoogleAuthProvider实例,避免隐性错误。

修正后的完整代码

Auth类代码

import { getAuth, signInWithPopup } from 'firebase/auth';
import { google } from './providers';

export default class Auth {
    constructor() {
        this.auth = getAuth();
    }

    static instance = new Auth();

    signInWithGoogle = async () => {
        try {
            return await signInWithPopup(this.auth, google);
        } catch (err) {
            console.error(err);
            throw new Error(err.message || '登录失败');
        }
    };

    static currentUser() {
        // 通过单例实例访问auth属性
        return this.instance.auth.currentUser;
    }
}

providers.js代码(确保正确初始化)

import { GoogleAuthProvider } from 'firebase/auth';

export const google = new GoogleAuthProvider();
// 可选:添加自定义参数,比如强制用户选择账号
google.setCustomParameters({ prompt: 'select_account' });

使用示例

// 调用Google登录
await Auth.instance.signInWithGoogle();

// 获取当前登录用户
const currentUser = Auth.currentUser();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:21