Flow(InferError):无法调用等待 'axios.get(...)' 绑定到 'p'

Flow(InferError): Cannot call await with 'axios.get(...)' bound to 'p'

我在使用 axios 时遇到一些 Flow 错误。

Cannot call await with 'axios.get(...)' bound to 'p' because:
Either property 'error_message' is missing in 'AxiosXHR'. 
Or property 'data' is missing in 'Promise'

这是我的代码,带有尝试的类型注释。 (没有 AxiosPromise<Object> 注释的相同错误。)错误在 axios.get(url).

  async handleAddressChange(): AxiosPromise<Object> {
    const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${GoogleMapsApiKey}&input=${this.state.address}`;
    try {
      const { data, error_message } = await axios.get(url);
      if (error_message) throw Error(error_message);
      this.setState({
        addressPredictions: data.predictions,
        showPredictions: true
      });
    } catch (err) {
      console.warn(err);
    }
  }

有趣的是,在另一个文件中 axios 没有给出 Flow 问题:

export async function loginWithApi(creds: AuthParams) {
  const res = await axios.get(ApiUrls.login, { params: creds });
  return res.data;
}

我的文件中有 import type { AxiosPromise, $AxiosXHR } from "axios";

有人知道如何解决这个问题吗?

如果出现错误,returned payload 中将没有 error_message,但错误会进入 catch 块。

另外,handleAddressChange 不是 returns AxiosPromise,而是 returns 隐式 promise,正如它用 async[ 定义的那样=21=]

所以,像这样:

async handleAddressChange(): Promise<void> {
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${GoogleMapsApiKey}&input=${this.state.address}`;
    try {
      const { data } = await axios.get(url);
      this.setState({
        addressPredictions: data.predictions,
        showPredictions: true
      });
    } catch (err: AxiosError) {
      new Error(err);
    }
  }

可能对你有用。请注意 AxiosError 定义。

需要注意的一点是,您可以将返回的负载添加到 AxiosPromise 泛型中,即:

type TExpectedLoginResponse = {
    ok: boolean,
    token: string
}

export async function loginWithApi(creds: AuthParams): AxiosPromise<TExpectedLoginResponse> {
  const res = await axios.get(ApiUrls.login, { params: creds });
  return res.data; // so now flow knows that res.data is type of TExpectedLoginResponse
}

希望对您有所帮助。