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

点击按钮加载Grid数据时报Uncaught (in promise) TypeError:无法读取undefined的dataState属性

错误根因

  • fetchAllData 是定义在App类组件外部的独立函数,没有绑定App组件的this上下文,执行时this指向为undefined,调用this.state.dataState自然触发类型错误。
  • fetchAllData、FirstButton都独立在App组件外,无法直接访问App组件内部的state和setState方法,数据请求后也没法把数据同步到Grid绑定的状态里。

修复方案

第一步:把数据请求逻辑移到App组件内部,绑定this

把外部的fetchAllData函数移到App类里,改成类的箭头函数方法,自动绑定this上下文:

class App extends React.PureComponent {
  state = {
    dataState: initialDataState,
    result: processWithGroups(initialDataState.products, initialDataState),
    collapsedState: [],
    products: [],
  };
  // 移到组件内部,用箭头函数绑定this
  fetchAllData = () => {
    fetch(
      'https://otp.metroservices.io/otp/routers/default/index/routes/uscalacmtarail:801/stops'
    )
      .then((response) => response.json())
      .then((productsList) => {
        const newDataState = processWithGroups(
          productsList,
          this.state.dataState
        );
        this.setState({
          products: productsList,
          result: newDataState,
        });
      });
  };
  // 其他原有方法保持不变
}

第二步:调整按钮调用逻辑,绑定组件内部的请求方法

二选一即可:

方案A(更简单):直接把按钮写在App的render方法中,删掉独立的FirstButton组件

render() {
  const newData = setExpandedState({
    data: this.state.result.data,
    collapsedIds: this.state.collapsedState,
  });
  return (
    <div>
      {/* 直接渲染按钮,绑定内部方法 */}
      <div>
        <button type="button" onClick={this.fetchAllData}>
          Fetch Products
        </button>
      </div>
      <Grid
        {/* 原有Grid配置保持不变 */}
      >
        {/* 原有Column配置保持不变 */}
      </Grid>
    </div>
  );
}

方案B:保留FirstButton组件,通过props传递请求方法

// 改造FirstButton接收触发请求的props
const FirstButton = (props) => {
  return (
    <div>
      <button type="button" onClick={props.onFetch}>
        Fetch Products
      </button>
    </div>
  );
};
// App的render中传递请求方法
render() {
  // 原有逻辑不变
  return (
    <div>
      <FirstButton onFetch={this.fetchAllData} />
      {/* 原有Grid配置保持不变 */}
    </div>
  )
}

如果要启用之前注释的组件挂载自动请求逻辑,直接打开注释即可,调整后this.fetchAllData()调用不会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:54:03