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

React + Firebase邮箱密码注册用户显示为匿名问题求助

React + Firebase Auth注册用户显示为匿名的问题

我开发了一个基于React的简易注册应用,采用Firebase Authentication实现身份验证,使用邮箱密码方式注册用户。各项功能运行看似正常,但注册后的用户却显示为(匿名)。我已在Firebase控制台启用了邮箱/密码验证方式,且代码中调用了createUserWithEmailAndPassword()函数。

相关代码如下:

import React from "react";
import Card from "@mui/material/Card";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import CardContent from "@mui/material/CardContent";
import Button from "@mui/material/Button";
import Alert from "@mui/material/Alert";
import { auth } from "./../firebase";
import { Link } from "react-router-dom";
import GoogleButton from "react-google-button";
import { GoogleAuthProvider, signInWithRedirect } from "firebase/auth";

export const Signup: React.FC = () => {
const emailRef = React.useRef<any>();
const passwordRef = React.useRef<any>();
const passwordConfirmRef = React.useRef<any>();
const [error, setError] = React.useState("");
const [loading, setLoading] = React.useState<boolean>(false);

const googleSignIn = () => {
  const provider = new GoogleAuthProvider();
  // signInWithPopup(auth, provider);
  signInWithRedirect(auth, provider);
};

async function handleSubmit(e: any) {
  e.preventDefault();
  if (passwordRef.current.value !== passwordConfirmRef.current.value) {
    return setError("Passwords do not match");
  }

  try {
    setError("");
    setLoading(true);
    await auth.createUserWithEmailAndPassword(
      emailRef.current!.value,
      passwordRef.current!.value
    );
  } catch {
    setError("Failed to create an account");
  }
  setLoading(false);
}
const handleGoogleSignIn = async () => {
  try {
    await googleSignIn();
  } catch (error) {
    console.log(error);
  }
};

return (
  <>
    <Card sx={{ width: "400px" }}>
      <CardContent>
        <Typography textAlign="center" variant="h4" m={2}>
          Sign Up
        </Typography>
        {error && (
          <Alert severity="error" sx={{ marginBottom: 2 }}>
            Passwords do not match
          </Alert>
        )}
        <form onSubmit={handleSubmit}>
          <Grid
            container
            direction="column"
            justifyContent="center"
            alignItems="stretch"
            gap={2}
          >
            <Grid xs={12} sm={6} item>
              <TextField
                label="Email"
                type="email"
                autoComplete="email"
                placeholder="Enter your email"
                variant="outlined"
                fullWidth
                required
                ref={emailRef}
              />
            </Grid>
            <Grid xs={12} sm={6} item>
              <TextField
                label="New Password"
                type="password"
                autoComplete="new-password"
                placeholder="New Password"
                variant="outlined"
                fullWidth
                required
                ref={passwordRef}
              />
            </Grid>
            <Grid xs={12} sm={6} item>
              <TextField
                label="Confirm Password"
                type="password"
                autoComplete="new-password"
                placeholder="Confirm New Password"
                variant="outlined"
                fullWidth
                required
                ref={passwordConfirmRef}
              />
            </Grid>
          </Grid>
          <Button
            type="submit"
            variant="contained"
            sx={{ marginTop: 2 }}
            fullWidth
            disabled={loading}
          >
            Sign Up
          </Button>
        </form>
      </CardContent>
    </Card>
    <Box component="div" marginTop={2} textAlign="center">
      <GoogleButton
        style={{ width: "100%", marginBottom: 15 }}
        onClick={handleGoogleSignIn}
      />
      <Typography
        variant="body1"
        component="a"
        href="#"
        sx={{ textDecoration: "none" }}
      >
        <Link to="/login" style={{ textDecoration: "none" }}>
          Already have an account? Log in
        </Link>
      </Typography>
    </Box>
  </>
);
};

问题截图:
用户显示为匿名的截图

解决方案
  • 确认Firebase Auth实例初始化正确性
    检查./../firebase文件中auth的导出代码,确保是基于正确的Firebase应用实例创建的,避免错误初始化导致匿名用户实例。正确的初始化示例:

    import { initializeApp } from "firebase/app";
    import { getAuth } from "firebase/auth";
    
    const firebaseConfig = {
      // 你的项目配置参数
    };
    
    const app = initializeApp(firebaseConfig);
    export const auth = getAuth(app);
    
  • 验证用户创建后的状态
    在createUserWithEmailAndPassword调用完成后,添加日志输出当前用户信息,确认用户是否被正确创建:

    await auth.createUserWithEmailAndPassword(
      emailRef.current!.value,
      passwordRef.current!.value
    );
    // 打印当前用户信息
    console.log("已创建用户:", auth.currentUser);
    

    如果控制台输出的用户包含正确的邮箱和UID,说明用户创建正常,可能是Firebase控制台显示延迟,刷新控制台页面即可。

  • 排查匿名登录干扰逻辑
    检查应用其他组件或代码中是否存在signInAnonymously的调用,该操作会将当前用户切换为匿名状态,覆盖邮箱密码注册的用户会话。

  • 修复错误提示硬编码问题
    当前代码中错误提示组件固定显示"Passwords do not match",无法展示其他注册错误信息,建议修改为动态显示error状态值:

    {error && (
      <Alert severity="error" sx={{ marginBottom: 2 }}>
        {error}
      </Alert>
    )}
    

    这能帮助你更准确地排查注册过程中出现的具体问题。

  • 刷新Firebase控制台用户列表
    Firebase控制台的用户列表有时不会实时更新,手动刷新页面后再查看用户详情,确认是否仍显示为匿名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:40:27