首页 > 解决方案 > axios 请求在 useEffect 中返回 undefined

问题描述

当我尝试在 useEffect 钩子中发出 axios 请求时,它返回 undefined,
但是在 Inspect Mode 下的 Network request 中查看时发现它是成功的

api.js

import axios from "axios";

export default axios.create({
  baseURL: `https://jsonplaceholder.typicode.com`
});

PostService.js

import instance from "./api";

export default {
  getPost: () => {
    instance({
      method: "GET",
      url: "/posts"
    })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  }
};

应用程序.js

import "./styles.css";
import { useEffect } from "react";

import PostService from "./PostService";

export default function App() {
  useEffect(() => {
    async function fetchData() {
      const response = await PostService.getPost();
      console.log(response); //return undefined
    }
    fetchData();
  }, []);

  return (
   ...
  );
}

CodeSandBox:
https ://codesandbox.io/s/happy-leftpad-cz12i?file=/src/App.js

标签: javascriptreactjsaxiosreact-hooks

解决方案


return在你的PostService:

import instance from "./api";

export default {
  getPost: () => {
    return instance({
      method: "GET",
      url: "/posts"
    })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  }
};

没有return,PostService正在调用 api 并获取数据,但它不会将任何内容发送回fetchData调用它的函数。


推荐阅读