属性"data"在类型 | AxiosHttpResponse上不存在。

8 浏览
0 Comments

属性"data"在类型 | AxiosHttpResponse上不存在。

我有一个承诺,我用它来setState,当我获取特定用户的数据时。以下是该代码:

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'.
  Property 'data' does not exist on type 'void'.ts(2339)
---
any

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

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

HttpResponse的代码在这里:

export interface HttpResponse extends Promise> {}

我尝试了类似这样的东西:

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

这是Axios接口:

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

请问您能解释一下问题是什么吗?我去看axios接口,我看到了数据和通用,没有问题...谢谢!!

admin 更改状态以发布 2023年5月24日
0
0 Comments

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

所以您必须像这样检查:

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

0