使用Supabase Auth的Expo应用中Session始终返回undefined
Expo + Supabase 账号页面Session返回undefined问题排查与解决
我按照官方示例开发Expo + Supabase应用,登录和账号创建功能正常,但进入账号页面后,即使用户已登录,session仍返回undefined。相关代码片段如下:
import { useState, useEffect } from 'react' import { supabase } from '../lib/supabase' import { StyleSheet, View, Alert } from 'react-native' import { Button, Input } from 'react-native-elements' import { Session } from '@supabase/supabase-js' export default function Account({ session }: { session: Session }) { const [loading, setLoading] = useState(true) const [username, setUsername] = useState('') const [website, setWebsite] = useState('') const [avatarUrl, setAvatarUrl] = useState('') useEffect(() => { if (session) getProfile() }, [session]) async function getProfile() { try { setLoading(true) if (!session?.user) throw new Error('No user on the session!')
排查与解决方法
检查父组件的session传递逻辑
Account组件的session依赖props传入,需确认父组件(如导航/路由组件)是否正确获取并传递会话:父组件应通过supabase.auth.onAuthStateChange监听状态变化,或调用supabase.auth.getSession()主动获取会话,再将其传递给Account组件。在组件内部主动获取session
绕过props传递的潜在问题,直接在Account组件内从Supabase获取会话,并监听状态变化:useEffect(() => { const fetchSessionAndProfile = async () => { const { data: { session } } = await supabase.auth.getSession() if (session) getProfile(session) } fetchSessionAndProfile() // 监听会话状态变更 const subscription = supabase.auth.onAuthStateChange((_event, session) => { if (session) getProfile(session) }) return () => subscription.unsubscribe() }, []) // 修改getProfile函数,接收session参数 async function getProfile(session: Session) { try { setLoading(true) if (!session?.user) throw new Error('No user on the session!') // 后续业务逻辑... } catch (error) { Alert.alert((error as Error).message) } finally { setLoading(false) } }验证Supabase客户端初始化
检查../lib/supabase中的客户端配置,确保SUPABASE_URL和SUPABASE_ANON_KEY正确,且Expo环境下已配置好异步存储(如@supabase/auth-storage-expo)。检查路由守卫的状态验证
若账号页面需登录访问,确认路由守卫是否正确验证登录状态,且跳转时已确保Supabase完成会话恢复。
内容的提问来源于stack exchange,提问作者herbie
相关产品推荐
相关产品推荐

