You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目调用YouTube API时出现Cannot read properties of undefined错误求助

解决React调用YouTube Data API时的Cannot read properties of undefined (reading 'ytData')错误

错误原因

这个报错是因为handleResponse方法中的this指向不是组件实例,导致无法访问this.ytData。当你直接把this.handleResponse传给fetch().then()时,方法的上下文丢失,在严格模式下this会变成undefined。

解决方案

方法1:在构造函数中绑定this

在组件的constructor里手动绑定handleResponse的this指向组件实例:

const url = `https://www.googleapis.com/youtube/v3/channels?key=${youtubeKeys.key}&part=statistics&id=${youtubeKeys.id}`

class Homepage extends React.Component {
  constructor() {
    super()
    this.ytData = []
    // 绑定this到组件实例
    this.handleResponse = this.handleResponse.bind(this)
  }

  getData() {
    fetch(url).then(this.handleResponse)
  }

  handleResponse(response) {  
    response.json().then((json) => {
      console.log(this.ytData)
      this.ytData.push(json.items[0].statistics)
      console.log(this.ytData)
    })
  }

  componentDidMount() {
    console.log(this.ytData)
    this.getData()
  }
}

方法2:用箭头函数定义handleResponse

箭头函数会自动继承外层上下文的this,直接把方法定义成箭头函数即可:

const url = `https://www.googleapis.com/youtube/v3/channels?key=${youtubeKeys.key}&part=statistics&id=${youtubeKeys.id}`

class Homepage extends React.Component {
  constructor() {
    super()
    this.ytData = []
  }

  getData() {
    fetch(url).then(this.handleResponse)
  }

  // 箭头函数自动绑定this
  handleResponse = (response) => {  
    response.json().then((json) => {
      console.log(this.ytData)
      this.ytData.push(json.items[0].statistics)
      console.log(this.ytData)
    })
  }

  componentDidMount() {
    console.log(this.ytData)
    this.getData()
  }
}

方法3:调用then时用箭头函数包裹

在getData方法中,用箭头函数调用handleResponse,确保this指向正确:

const url = `https://www.googleapis.com/youtube/v3/channels?key=${youtubeKeys.key}&part=statistics&id=${youtubeKeys.id}`

class Homepage extends React.Component {
  constructor() {
    super()
    this.ytData = []
  }

  getData() {
    // 用箭头函数包裹,传递正确的this
    fetch(url).then((response) => this.handleResponse(response))
  }

  handleResponse(response) {  
    response.json().then((json) => {
      console.log(this.ytData)
      this.ytData.push(json.items[0].statistics)
      console.log(this.ytData)
    })
  }

  componentDidMount() {
    console.log(this.ytData)
    this.getData()
  }
}

额外建议

在React类组件中,直接修改this.ytData不会触发组件重新渲染。如果后续需要用这个数据渲染UI,建议把ytData放到组件的state中管理:

constructor() {
  super()
  this.state = {
    ytData: []
  }
}

// 更新数据时用setState
handleResponse = (response) => {  
  response.json().then((json) => {
    this.setState(prevState => ({
      ytData: [...prevState.ytData, json.items[0].statistics]
    }))
  })
}

内容的提问来源于stack exchange,提问作者jvn11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 05:15:31