首页 > 解决方案 > 来自 axios 操作创建者的未定义响应

问题描述

我正在重构我的动作创建者并遇到了一个错误。基本上,这个动作是发送一个“get”请求,它应该检索一条消息和一个状态代码(现在我至少尝试获取消息)。在浏览器中,当我打开网络选项卡时,请求已发送,但是我的控制台日志返回未定义。谁能帮我解决这个问题。这是动作创建者本身:

export const handleFetchData =
  (accessToken: string, refreshToken: string) => async (dispatch: Function) => {
    try {
      const response = await mainApiProtected.mePage({});
      console.log(response);
    } catch (error) {
      console.log(error);
    }
};

以下是支持 TypeScript 文件:

import { AxiosRequestConfig } from "axios";
import HttpClientProtected from "./HttpClientProtected";

class MainProtected extends HttpClientProtected {
  private static instanceCached: MainProtected;

  private constructor() {
    super("http://142.93.134.108:1111/");
  }

  static getInstance = () => {
    if (!MainProtected.instanceCached) {
      MainProtected.instanceCached = new MainProtected();
    }

    return MainProtected.instanceCached;
  };

  public mePage = (body: AxiosRequestConfig) => {
    this.instance.get<{ message: string }>("/me", body);
  };
}

export default MainProtected;
import { AxiosRequestConfig, AxiosResponse } from "axios";
import HttpClient from "./HttpClient";

abstract class HttpClientProtected extends HttpClient {
  constructor(baseURL: string) {
    super(baseURL);

    this.initializeRequestInterceptors();
  }

  private initializeRequestInterceptors = () => {
    this.instance.interceptors.request.use(this.handleMe);
    this.instance.interceptors.response.use(this.handleMeResponse);
  };

  private handleMe = (config: AxiosRequestConfig) => {
    const accessToken = localStorage.getItem("accessToken");

    const updatedConfig = config;
    updatedConfig.headers.Authorization = `Bearer ${accessToken}`;

    return updatedConfig;
  };

  private handleMeResponse = ({ data }: AxiosResponse) => data;
}

export default HttpClientProtected;

标签: typescriptreduxaxios

解决方案


看起来您mePage实际上并没有返回 Promise 或任何东西:

  public mePage = (body: AxiosRequestConfig) => {
    this.instance.get<{ message: string }>("/me", body);
  };

您可能打算在此处添加一个return,或删除{ }括号以进行隐式返回。


推荐阅读