类型 <void> 上不存在属性 `data` | AxiosHttpResponse<any>

Dim*_*fst 4 javascript typescript reactjs axios

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

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
          });
        }
      });
Run Code Online (Sandbox Code Playgroud)

但我收到这个 TS 错误说:

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

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

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

HttpResponse 的代码在这里:

export interface HttpResponse<T> extends Promise<void | AxiosResponse<T>> {}
Run Code Online (Sandbox Code Playgroud)

我试过类似的东西:

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

这是 Axios 接口:

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}
Run Code Online (Sandbox Code Playgroud)

你能向我解释一下是什么问题。我去axios界面,看到了datageneric也没有问题..谢谢!!

Sna*_*rak 6

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

所以你必须像这样检查:

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