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

React(TypeScript)项目中Axios请求出现Promise<pending>问题求助

解决React(TypeScript)中Axios GET请求返回Promise的问题

问题原因

getsongs()是异步函数,调用后会直接返回一个Promise对象,而不是请求完成后的实际歌曲数据,所以finaldata会处于pending状态。


解决方案

方法1:React组件内标准异步数据获取方式(推荐)

在组件中通过useEffect触发请求,配合useState管理数据、加载状态和错误状态,这是React中处理异步数据的常规方案:

import axios from 'axios';
import { useEffect, useState } from 'react';

interface Song {
  name: string;
}

interface Playlist {
  playlistname: string;
  songs: Song[];
}

async function getSongs(): Promise<Song[]> {
  const url = 'https://be-ask.tanaypratap.repl.co/playlist';
  const response = await axios.get<Playlist>(url);
  return response.data.songs;
}

export default function SongListComponent() {
  const [songs, setSongs] = useState<Song[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchSongs = async () => {
      try {
        const songData = await getSongs();
        setSongs(songData);
      } catch (err) {
        setError(err instanceof Error ? err.message : '请求失败');
      } finally {
        setLoading(false);
      }
    };

    fetchSongs();
  }, []);

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误:{error}</div>;

  return (
    <div>
      <h2>歌曲列表</h2>
      <ul>
        {songs.map((song, idx) => (
          <li key={idx}>{song.name}</li>
        ))}
      </ul>
    </div>
  );
}

方法2:模块级别立即执行异步函数(不推荐在组件场景使用)

如果需要在模块初始化时获取数据(但无法触发React组件重新渲染,仅适用于非组件场景):

import axios from 'axios';

interface Song {
  name: string;
}

interface Playlist {
  playlistname: string;
  songs: Song[];
}

async function getSongs(): Promise<Song[]> {
  const url = 'https://be-ask.tanaypratap.repl.co/playlist';
  const response = await axios.get<Playlist>(url);
  return response.data.songs;
}

let finaldata: Song[] | null = null;
let isLoading = true;
let requestError: string | null = null;

// 立即执行异步函数处理结果
(async () => {
  try {
    finaldata = await getSongs();
  } catch (err) {
    requestError = err instanceof Error ? err.message : '请求失败';
  } finally {
    isLoading = false;
  }
})();

export { finaldata, isLoading, requestError };

核心注意事项

  • 异步函数必须通过await或.then()才能获取最终结果,直接调用只会得到Promise对象。
  • React组件中务必使用useEffect触发异步请求,配合状态管理实现页面的动态更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:20:20