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

使用TopoJSON开发项目遇报错:Cannot read property 'objects' of undefined求助

解决TopoJSON加载时"Cannot read property 'objects' of undefined"报错

嘿,我发现你遇到的问题其实是Promise.all使用时的一个常见小坑!

问题出在哪?

Promise.all()完成后,会把所有异步请求的结果打包成一个数组传给.then()的回调函数,但你现在的回调函数写法是把它当成三个独立参数来接收的:

function callback(csvData, statesUS, countiesUS) { /* ... */ }

这就导致csvData实际上是包含三个数据的数组,而statesUS和countiesUS全是undefined——这就是为什么你调用statesUS.objects时会触发那个报错!

怎么改?

最简单的办法是用ES6的数组解构来直接获取三个数据,代码会更清晰:

Promise.all(promises).then(([csvData, statesUS, countiesUS]) => {
    // 放置经纬网
    setGraticule(map, path)
    // 转换TopoJSON数据
    const usStates = topojson.feature(
        statesUS, statesUS.objects.cb_2018_us_state_5m
    )
    const usCounties = topojson.feature(countiesUS, countiesUS.objects.counties).features
})

如果你不想用箭头函数,也可以手动从结果数组里提取:

function callback(results) {
    const csvData = results[0]
    const statesUS = results[1]
    const countiesUS = results[2]
    // 后面的逻辑不变...
    setGraticule(map, path)
    const usStates = topojson.feature(
        statesUS, statesUS.objects.cb_2018_us_state_5m
    )
    const usCounties = topojson.feature(countiesUS, countiesUS.objects.counties).features
}
Promise.all(promises).then(callback)

万一修正后还是有问题?

虽然你说CSV和counties数据关联成功,但可以再做几个检查:

  • 确认states.topojson的文件路径完全正确,而且文件里确实有objects.cb_2018_us_state_5m这个结构(可以在控制台执行console.log(statesUS)查看具体内容)
  • 检查TopoJSON文件本身有没有语法错误,比如括号没闭合、逗号漏写之类的问题
  • 确保你的topojson库版本和d3版本是兼容的,不同版本的API可能存在差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:52:42