React+TypeScript项目中Axios GET请求后无法访问response.data报错
Hey there! Let's break down why you're hitting this TypeScript error and how to fix it quickly.
The Root Cause
When you chain .catch(error => console.log(error)) onto your axios.get call, that catch callback doesn't return any value—it just logs the error. TypeScript sees this and infers that the result of your await expression could be either a valid AxiosResponse (on success) or void (on failure, since the catch returns nothing).
Since void translates to undefined at runtime, TypeScript won't let you access response.data directly—it's protecting you from a potential "cannot read property 'data' of undefined" crash if the request fails.
Solution 1: Use try/catch (Recommended)
This is the cleanest approach for async/await code, and it keeps TypeScript's type inference working correctly:
const fetchItem = async () => { try { // TypeScript knows response is definitely an AxiosResponse here const response = await axios.get("http://localhost:4000/items?id=2"); console.log(response.data); } catch (error) { console.log(error); // Add any other error handling here (e.g., set an error state for your UI) } };
With this setup, the response variable is only defined in the try block where the request succeeded, so TypeScript can safely confirm it has a data property.
Solution 2: Return a Fallback in .catch (If You Prefer Chaining)
If you really want to keep the chained .catch, you need to make sure it returns a value that matches the AxiosResponse type. This tells TypeScript that response will always have a data property (even if it's a fallback):
import { AxiosResponse } from 'axios'; // Make sure to import this type const fetchItem = async () => { const response = await axios.get("http://localhost:4000/items?id=2") .catch((error) => { console.log(error); // Return a fallback response to satisfy TypeScript's type check return { data: null } as AxiosResponse; }); console.log(response.data); };
Note that this approach means you'll get null in response.data if the request fails—you'll need to handle that case in your code if necessary.
Why Solution 1 is Better
Using try/catch aligns with standard async/await patterns, makes your error handling more explicit, and avoids any ambiguity in TypeScript's type checking. It also prevents accidental runtime errors that could happen if you forget to handle the fallback case in Solution 2.
内容的提问来源于stack exchange,提问作者Tiago

