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

React Native+TS+Firestore项目auth属性不存在、error为unknown类型报错

报错原因与解决方案

报错产生原因

1. Property 'auth' does not exist on type 'typeof 报错

你使用的是Firebase v9及以上版本,该版本默认采用模块化API设计,已经移除了v8版本中全局firebase命名空间下挂载的auth等属性,你使用v8的写法调用自然找不到对应的类型与属性,触发TS报错。
你后续调整为v9写法后仍报错,是因为调用getAuth时传参错误:getAuth要求传入initializeApp返回的Firebase应用实例,你错误传入了自定义的initialFirebase函数;同时调用createUserWithEmailAndPassword时直接写auth,没有加this.访问类属性,导致变量未定义。

2. Object is of type 'unknown'.ts(2571) 报错

TypeScript 4.4及以上版本默认将catch块捕获的error类型设置为unknown,unknown类型不允许直接访问任意属性,必须先完成类型收窄或类型断言才能访问code属性。

修复步骤

第一步:修正Firebase初始化与auth实例逻辑

import {initializeApp, FirebaseApp, FirebaseError} from 'firebase/app';
import {firebaseConfig} from '../config/config';
import {getAuth, createUserWithEmailAndPassword, Auth} from 'firebase/auth';

export interface Props {}
interface State {
  email: string;
  password: string; // 建议改为string类型,不要用any
  isLoading: boolean;
}

export default class LoginScreen extends React.Component<Props, State> {
  // 声明Firebase实例与auth实例属性
  private firebaseApp: FirebaseApp;
  private auth: Auth;

  constructor(props: Props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      isLoading: false,
    };
    // 直接初始化Firebase,保存实例
    this.firebaseApp = initializeApp(firebaseConfig);
    // 传入Firebase实例获取auth对象
    this.auth = getAuth(this.firebaseApp);
  }

第二步:修正注册逻辑与catch块类型处理

onSignUp = async () => {
  if (this.state.email && this.state.password) {
    try {
      const response = await createUserWithEmailAndPassword(
        this.auth,
        this.state.email,
        this.state.password,
      );
      // 可补充注册成功后的跳转逻辑
    } catch (error) {
      // 先判断是否为FirebaseError类型,再访问code属性
      if (error instanceof FirebaseError && error.code === 'auth/email-already-in-use') {
        Alert.alert('Signup Error', 'User already exist!', [
          {
            text: 'Ok',
          },
        ]);
      }
    }
  }
};

额外补充:修正TextInput的状态更新逻辑

原有代码中TextInput的onChangeText写法错误,直接传值给setState不会更新对应状态,需要改为:

<TextInput
  placeholder="Your Email"
  keyboardType="email-address"
  autoCorrect={false}
  style={styles.txtInput}
  onChangeText={(email) => this.setState({email})} // 传入状态对象
/>
<TextInput
  placeholder="Your Password"
  secureTextEntry
  style={styles.txtInput}
  onChangeText={(password) => this.setState({password})} // 传入状态对象
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:15:02