【问题标题】:Property `data` does not exist on Type <void> | AxiosHttpResponse<any>类型 <void> 上不存在属性 `data` | AxiosHttpResponse<任意>
【发布时间】:2019-08-16 22:45:17
【问题描述】:

我有一个承诺,当我为特定用户获取数据时,我使用它来设置状态。下面是代码:

getUserUsername = (): string => {
    const { match } = this.props;
    return match.params.username;
  };

  onFetchUser = () =>
    getUser(this.getUserUsername())
      .then(username => {
        if (this.hasBeenMounted) {
          this.setState({
            user: username.data // The error is here.
          });
        }
      })
      .catch((errorResponse: HttpResponseObj | null = null) => {
        if (this.hasBeenMounted) {
          this.setState({
            isLoading: false,
            user: null,
            errorMessage: errorResponse
          });
        }
      });

但我收到此 TS 错误提示:

Property 'data' does not exist on type 'void | AxiosResponse<IUser>'.
  Property 'data' does not exist on type 'void'.ts(2339)
---
any

getUser(),是我使用的一项服务,它的代码在这里:

export const getUser = (username: string, initialOptions = {}): HttpResponse<IUser> => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.GET_USER(username)
  };
  return Instance(options, lensesOptions);
};

HttpResponse 的代码在这里:

export interface HttpResponse<T> extends Promise<void | AxiosResponse<T>> {}

我尝试了类似的方法:

      .then((username): HttpResponse<any> => { // Doesn't work though
        if (this.hasBeenMounted) {
          this.setState({
            user: username.data
          });
        }
      })

这里是 Axios 接口:

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

你能解释一下是什么问题吗?我去axios界面看到data,还有generic没问题。。谢谢!!

【问题讨论】:

    标签: javascript reactjs typescript axios


    【解决方案1】:

    您必须在尝试使用之前检查username 的类型,因为该函数返回两个具有不同属性的值(void 和 AxiosResponse)

    所以你必须像这样检查:

      .then(username => {
        // Check if it is not void
        if (this.hasBeenMounted && username ) { 
          this.setState({
            user: username.data
          });
        }
      })
    

    【讨论】:

    • 好的,他们都工作了。一个问题。现有答案与您之前发布的答案之间有什么区别。 username !== undefined &amp;&amp; username.data !== typeof username !== 'undefined'.
    • 查看我的最新更新。用户名可以是nullundefined,因为void 是其中的supertype。因此,如果您只检查用户名值 it evaluates null and undefined 等。不要使用我之前的答案 (typeof username !== 'undefined'),因为我利用了可能的打字稿错误。我创建了一个question to understand it
    猜你喜欢
    • 2019-12-01
    • 2019-03-18
    • 2018-08-11
    • 2021-08-05
    • 1970-01-01
    • 2022-01-27
    • 2021-12-11
    • 2016-12-31
    • 2019-02-04
    相关资源
    最近更新 更多