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

TypeScript中异步函数调用及onAuthStateChanged异步回调类型标注问题

TypeScript异步函数调用与回调类型报错解决

一、TypeScript中调用这类异步函数的方法

你的onUserStateChange函数用于监听Firebase用户状态变化,调用时只需传入处理用户状态更新的回调函数即可,分两种场景:

React组件中调用

结合React的useState和useEffect使用,同时注意清理监听避免内存泄漏:

import { onUserStateChange } from './auth-utils'; // 替换为你的实际文件路径
import { useState, useEffect } from 'react';
import { User } from 'firebase/auth';

export default function UserProfile() {
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  useEffect(() => {
    // 调用监听函数,传入setState作为状态更新回调
    const unsubscribe = onUserStateChange(setCurrentUser);
    // 组件卸载时取消监听
    return unsubscribe;
  }, []);

  return (
    <div>
      {currentUser ? (
        <div>
          <p>邮箱:{currentUser.email}</p>
          <p>{currentUser.isAdmin ? '管理员' : '普通用户'}</p>
        </div>
      ) : (
        <p>未登录</p>
      )}
    </div>
  );
}

非React环境调用

直接传入自定义回调处理用户状态:

import { onUserStateChange } from './auth-utils';
import { User } from 'firebase/auth';

onUserStateChange((updatedUser: User | null) => {
  console.log('当前用户状态:', updatedUser);
  // 这里可执行全局状态更新、页面跳转等后续逻辑
});

二、解决onAuthStateChanged异步回调的类型报错

报错Promise returned in function argument where a void return was expected.的核心原因:onAuthStateChange要求回调函数返回void,但你使用了async函数——这类函数默认会返回Promise,和预期返回类型不匹配。

最优解决方案:用IIFE包裹异步逻辑

将异步代码放在立即执行的异步函数表达式中,让外层回调保持返回void:

type DispatchType = Dispatch<SetStateAction<User | null>>;

export function onUserStateChange(callback: DispatchType) {
  onAuthStateChanged(auth, (user: User | null) => {
    // 用IIFE包裹异步操作,避免外层回调返回Promise
    (async () => {
      const updatedUser = user ? await adminUser(user) : null;
      callback(updatedUser);
    })();
  });
}

async function adminUser(user: User | null) {
  return get(ref(database, 'admins')).then((snapshot) => {
    if (snapshot.exists()) {
      const admins = snapshot.val();
      // 注意:数组方法是includes,不是include,此处修正拼写错误
      const isAdmin = admins.includes(user?.uid);
      return { ...user, isAdmin };
    }
    return user;
  });
}

额外提示

你的adminUser函数存在拼写错误:admins.include(user?.uid)需改为admins.includes(user?.uid),否则会触发运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:40:21