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

React Native AsyncStorage getItem使用异常,求正确调用方法

Hey there! That strange {"40":0,"_65":0,"_55":null,"_72":null} value you're getting is actually a mis-handled Promise object. The issue comes from mixing async/await and callback-style handling in your getItem call—AsyncStorage's getItem behaves differently depending on whether you pass a callback or not. Let me walk you through the correct ways to use it:

First: Make sure you're using the right package

In modern React Native, the core AsyncStorage has been moved to a separate package. So first, ensure you've installed and imported it correctly:

import AsyncStorage from '@react-native-async-storage/async-storage';

This is the cleanest and most readable way. Skip the callback entirely, use await to wait for the Promise to resolve, and wrap everything in a try/catch to handle errors:

async function addSessionId() {
  try {
    // Wait for getItem to resolve and get the actual value
    const sessionId = await AsyncStorage.getItem("session_id");
    console.warn(sessionId);
    return sessionId;
  } catch (error) {
    // Handle any errors (e.g., storage access issues)
    console.error('Failed to fetch session_id:', error);
    return null; // Or return a default value of your choice
  }
}

Correct Approach 2: Use Promise .then()/.catch()

If you prefer callback-style chaining instead of async/await, you can use the Promise-based API directly (no need for async/await here):

function addSessionId() {
  return AsyncStorage.getItem("session_id")
    .then(sessionId => {
      console.warn(sessionId);
      return sessionId;
    })
    .catch(error => {
      console.error('Failed to fetch session_id:', error);
      return null;
    });
}

Why your original code didn't work

When you pass a callback to getItem, the method doesn't return a Promise—it executes the callback with the result instead. But you tried to await this non-Promise return value, which wraps it in a resolved Promise, and you ended up seeing the internal state of that Promise object instead of your actual session_id.

How to call the function

No matter which approach you use, when you call addSessionId, you'll need to handle its async nature:

// Using async/await
async function useSession() {
  const id = await addSessionId();
  // Do something with id here
}

// Or using .then()
addSessionId().then(id => {
  // Do something with id here
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:04:29