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

React Native中useEffect内调用AsyncStorage.getItem报错,求排查

React Native中useEffect调用AsyncStorage.getItem报错问题

问题描述

在React Native项目的Pregent_login组件中,在useEffect钩子内调用AsyncStorage.getItem('token')时出现报错,相关代码如下:

export default function Pregent_login(props) {
  const [first, setfirst] = useState();
  useEffect(() => {
    console.log('route.params ==>', props.route.params);

     const value = AsyncStorage.getItem('token');
     setfirst(value);
  }, []);

错误原因

AsyncStorage.getItem()是异步方法,它返回的是一个Promise对象,而非直接的token字符串值。你直接将这个Promise对象赋值给first状态,会导致后续使用该状态时出现异常,这就是报错的核心原因。

解决方法

方法1:使用async/await处理异步逻辑

将useEffect的回调内定义异步函数,通过await获取实际的token值:

export default function Pregent_login(props) {
  const [first, setfirst] = useState();
  useEffect(() => {
    console.log('route.params ==>', props.route.params);
    
    const getToken = async () => {
      try {
        const value = await AsyncStorage.getItem('token');
        setfirst(value);
      } catch (error) {
        console.error('获取token失败:', error);
      }
    };

    getToken();
  }, []);

方法2:使用Promise链式调用

通过then/catch处理异步结果和错误:

export default function Pregent_login(props) {
  const [first, setfirst] = useState();
  useEffect(() => {
    console.log('route.params ==>', props.route.params);
    
    AsyncStorage.getItem('token')
      .then(value => {
        setfirst(value);
      })
      .catch(error => {
        console.error('获取token失败:', error);
      });
  }, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:25:26