调用异步通知权限检查函数返回对象而非布尔值的问题求解
问题原因
所有async函数的返回值默认都是Promise类型,你直接调用异步函数不做await处理时,拿到的永远是Promise实例而非内部返回的布尔值。同时useState的初始化参数是同步执行的,无法直接接收异步操作的返回结果。
代码优化
首先你的权限检查函数可以简化写法,不需要混用await和then,两种异步处理方式选其一即可:
notificationsAllowed = async () => { const res = await requestNotifications(['alert', 'sound']); return res.status === "granted"; }
解决方案(全React版本兼容)
在函数式组件内,通过useEffect钩子执行异步逻辑,拿到结果后再更新状态:
// 初始化状态可设为默认值,比如false代表默认未开启,或设为null代表加载中 const [isEnabled, setIsEnabled] = useState(false); // 可选:加载状态用于控制开关的禁用态/加载动画 const [isLoading, setIsLoading] = useState(true); useEffect(() => { // 在useEffect内部定义异步函数执行权限检查 const checkNotificationPermission = async () => { try { const allowed = await NotificationsManager.getInstance().notificationsAllowed(); setIsEnabled(allowed); } catch (error) { // 可自行添加错误处理逻辑,比如权限请求失败提示 setIsEnabled(false); } finally { setIsLoading(false); } } checkNotificationPermission(); }, []); // 空依赖数组代表组件挂载时仅执行一次
可选方案(React 18+)
如果你的项目使用React 18及以上版本,也可以通过use钩子直接消费Promise,不过需要在外层包裹Suspense组件处理加载状态:
import { use, Suspense, useState } from 'react'; // 组件内部代码 const allowed = use(NotificationsManager.getInstance().notificationsAllowed()); const [isEnabled, setIsEnabled] = useState(allowed);
内容的提问来源于stack exchange,提问作者John Doah
相关产品推荐
相关产品推荐

