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

React Native中为何无法及时从AsyncStorage获取认证Token?

问题原因

你代码里的核心问题是async函数调用后返回的是Promise对象,而非实际的token值。getToken()执行后,你直接把这个Promise赋值给了token变量,当EventSource初始化时,token还是未resolve的Promise,而非你期望的字符串token,导致Authorization头无法正确生成。

解决方案

需要等待getToken()的Promise resolve拿到实际token后,再初始化EventSource。由于useEffect的回调不能直接是async函数,你可以在其内部定义一个async的初始化函数,然后执行它。

修正后的代码:

const App = () => {
    useEffect(() => {
        const url = `${api_root_url}/stream`;
        let eventSource = null;

        const getToken = async () => {
            const token = await AsyncStorage.getItem('token');
            return token ? JSON.parse(token) : null;
        };

        const initEventSource = async () => {
            const token = await getToken();
            // 没有token的话,直接返回,避免创建无效的EventSource
            if (!token) {
                console.log('未获取到授权Token');
                return;
            }

            eventSource = new EventSource(url, {
                headers: {
                    Authorization: `Bearer ${token}`
                },
            });

            eventSource.addEventListener('open', () => {
                console.log('SSE opened!');
            });

            eventSource.addEventListener('message', (e) => {
                console.log(typeof (e.data), e.data);
                const data = JSON.parse(e.data);
            });

            eventSource.addEventListener('error', (e) => {
                console.error('Error: ', e);
            });
        };

        initEventSource();

        return () => {
            if (eventSource) {
                eventSource.close();
            }
        };

    }, []);
};
关键改动说明
  • 新增initEventSource异步函数,在内部awaitgetToken()确保拿到实际的token值。
  • 将EventSource的创建逻辑放在token获取成功之后,保证Authorization头使用的是正确的字符串token。
  • 新增token为空的判断,避免创建无有效授权的EventSource。
  • 把eventSource变量提升到useEffect内部的顶层,确保在清理函数中可以正确关闭它。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 01:31:08