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

React Native报错TypeError: Cannot call a class as a function,求错误定位

Hey Paulo, let's dig into that TypeError: Cannot call a class as a function error you're hitting with your Firebase signup function! I can spot exactly where the issue is and how to fix it.

What's Causing the Error?

This error pops up because you're trying to call two Firestore classes like regular functions instead of instantiating them properly:

  1. firestore.GeoPoint(): GeoPoint is a class, so you need to use the new keyword to create an instance of it. Skipping new tells JavaScript to treat it as a regular function, which throws the error.
  2. firestore.Timestamp.fromDate(): Depending on your Firebase SDK version, Timestamp isn't a property of the Firestore database instance you get from firestore(). It's either a standalone export (in v9+ modular SDK) or lives under the main Firebase namespace (in v8).

Fixed Code for Your Scenario

Let's adjust your code based on two common Firebase SDK setups:

If you're using Firebase v8 (Namespace SDK)

const handleSignUp = useCallback(async data => {
  try {
    setLoading(true);
    const auth = await authFB().createUserWithEmailAndPassword(
      data.email,
      data.password,
    );
    const db = firestore();
    const firstName = data.name.split(' ').slice(0, -1).join(' ');
    const lastName = data.name.split(' ').slice(-1).join(' ');
    
    await db
      .collection('Providers')
      .doc(auth.user.uid)
      .set({
        id: auth.user.uid,
        name: {
          first: firstName,
          last: lastName,
        },
        email: data.email,
        createdAt: firebase.firestore.Timestamp.fromDate(new Date()), // Fixed Timestamp access
        address: {
          position: new firebase.firestore.GeoPoint( // Added `new` for GeoPoint
            coordinates.latitude,
            coordinates.longitude,
          ),
        },
      })
      .then(() => {
        navigation.reset({
          routes: [{ name: 'SignIn' }],
          index: 0,
        });
      });
    setLoading(false);
    Alert.alert(
      'Cadastro realizado com sucesso!',
      'Você já pode fazer login na aplicação.',
    );
  } catch (err) {
    console.error('Signup error:', err); // Add this to debug future issues
    setLoading(false);
  }
}, [coordinates, navigation]); // Added navigation to dependencies (important!)

If you're using Firebase v9+ (Modular SDK)

First, make sure you import the right Firestore tools:

import { getFirestore, doc, setDoc, Timestamp, GeoPoint } from "firebase/firestore";
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";

Then update your function:

const handleSignUp = useCallback(async data => {
  try {
    setLoading(true);
    const authInstance = getAuth();
    const userCredential = await createUserWithEmailAndPassword(
      authInstance,
      data.email,
      data.password,
    );
    const db = getFirestore();
    const firstName = data.name.split(' ').slice(0, -1).join(' ');
    const lastName = data.name.split(' ').slice(-1).join(' ');
    
    await setDoc(
      doc(db, 'Providers', userCredential.user.uid),
      {
        id: userCredential.user.uid,
        name: {
          first: firstName,
          last: lastName,
        },
        email: data.email,
        createdAt: Timestamp.fromDate(new Date()), // Use imported Timestamp
        address: {
          position: new GeoPoint( // Use imported GeoPoint with `new`
            coordinates.latitude,
            coordinates.longitude,
          ),
        },
      }
    ).then(() => {
      navigation.reset({
        routes: [{ name: 'SignIn' }],
        index: 0,
      });
    });
    setLoading(false);
    Alert.alert(
      'Cadastro realizado com sucesso!',
      'Você já pode fazer login na aplicação.',
    );
  } catch (err) {
    console.error('Signup error:', err); // Helpful for debugging
    setLoading(false);
  }
}, [coordinates, navigation]);

Quick Extra Tips

  • Adding console.error(err) in the catch block will show you detailed error messages next time something goes wrong, making debugging way easier.
  • Don't forget to add navigation to your useCallback dependencies array—missing this can cause unexpected behavior in React Native.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:24:34