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

使用Expo时应用崩溃,报错TypeError: undefined is not an object (evaluating 'items.forEach')

解决TypeError: undefined is not an object (evaluating 'items.forEach')崩溃问题

这个错误的核心是你代码里的items参数为undefined,而undefined没有forEach方法,调用时直接触发崩溃。

看你提供的_calcCardPositions和_initInterpolators两个方法,都是直接从props解构出items就调用forEach,完全没做存在性校验。

给你两种可行的修复方案:

  • 给items设置默认空数组
    在解构props时直接给items加默认值,确保它始终是数组类型:

    _calcCardPositions (props = this.props) {
        const { items = [], sliderWidth, itemWidth } = props;
    
        items.forEach((item, index) => {
            this._positions[index] = {
                start: index * itemWidth
            };
            this._positions[index].end = this._positions[index].start + itemWidth;
        });
    }
    
    _initInterpolators () {
        const { items = [], firstItem } = this.props;
        let interpolators = [];
    
        items.forEach((item, index) => {
            interpolators.push(new Animated.Value(index === firstItem ? 1 : 0));
        });
        this.setState({ interpolators });
    }
    
  • 调用forEach前先做非空判断
    如果不想用默认值,也可以在调用方法前检查items是否为有效数组:

    _calcCardPositions (props = this.props) {
        const { items, sliderWidth, itemWidth } = props;
    
        if (Array.isArray(items)) {
            items.forEach((item, index) => {
                this._positions[index] = {
                    start: index * itemWidth
                };
                this._positions[index].end = this._positions[index].start + itemWidth;
            });
        }
    }
    
    _initInterpolators () {
        const { items, firstItem } = this.props;
        let interpolators = [];
    
        if (Array.isArray(items)) {
            items.forEach((item, index) => {
                interpolators.push(new Animated.Value(index === firstItem ? 1 : 0));
            });
        }
        this.setState({ interpolators });
    }
    

另外建议检查父组件传递items的逻辑——是不是初始渲染时items还在异步加载(比如请求接口数据),导致第一次传过来的是undefined?如果是这种情况,在父组件里给items设初始空数组,能从源头避免问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:24:32