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

Alpine JS报错:Cannot read properties of undefined (reading 'title') 求助

排查Alpine JS打字组件的TypeError错误

错误原因分析

  • 异步请求竞态问题:fetch是异步操作,但你在请求还未返回数据时就启动了setInterval(startTyping, $data.typeSpeed),此时textArray还是初始的空数组,$data.textArray[$data.textIndex]为undefined,读取.title就会抛出Cannot read properties of undefined (reading 'title')错误。
  • API请求无错误处理:当前代码没有处理请求失败的情况,如果API返回错误(比如404、权限问题),textArray会保持空数组,同样会触发上述错误。
  • 缺少数据边界检查:未判断textArray是否为空或当前索引是否有效,直接访问元素的title属性。

修复后的代码

<div class="text-base w-56 px-5 rounded-full overflow-hidden" x-data="{
                   textArray: [],
                text: '',
                textIndex: 0,
                charIndex: 0,
                pauseEnd: 2750,
                cursorSpeed: 420,
                pauseStart: 20,
                typeSpeed: 50,
                direction: 'forward'
             }" x-init="(() => {
                let typingInterval;

                // 处理API请求,增加错误捕获
                fetch('/wp-json/wp/v2/pages/219/?_fields=acf.positions&acf_format=standard')
                  .then(response => {
                    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
                    return response.json();
                  })
                  .then(data => {
                    // 确保positions是数组,设置默认值
                    textArray = Array.isArray(data?.acf?.positions) ? data.acf.positions : [];
                    // 数据加载完成后再启动打字逻辑
                    if (textArray.length > 0) {
                      typingInterval = setInterval(startTyping, typeSpeed);
                    }
                  })
                  .catch(err => console.error('API请求失败:', err));

             function startTyping(){
                // 先检查数组是否为空,当前索引是否有效
                if (!textArray.length || !textArray[textIndex]) {
                  clearInterval(typingInterval);
                  return;
                }
                let current = textArray[textIndex].title;
                if(charIndex > current.length){
                     direction = 'backward';
                     clearInterval(typingInterval);
                     setTimeout(function(){
                        typingInterval = setInterval(startTyping, typeSpeed);
                     }, pauseEnd);
                }

                text = current.substring(0, charIndex);
                if(direction == 'forward'){
                    charIndex += 1;
                 } else {
                    if(charIndex == 0){
                        direction = 'forward';
                        clearInterval(typingInterval);
                        setTimeout(function(){
                            textIndex += 1;
                            if(textIndex >= textArray.length){
                                textIndex = 0;
                            }
                            typingInterval = setInterval(startTyping, typeSpeed);
                        }, pauseStart);
                    }
                    charIndex -= 1;
                 }
             }

             setInterval(function(){
                if($refs.cursor.classList.contains('hidden')){
                    $refs.cursor.classList.remove('hidden');
                } else {
                    $refs.cursor.classList.add('hidden');
                }
             }, cursorSpeed);
         })()">
            <span x-text="text"></span>
            <span class="opacity-70" x-ref="cursor">|</span>
        </div>

关键修复点

  • 将打字定时器的启动移到fetch的then回调内,确保数据加载完成后再执行打字逻辑。
  • 增加API请求的response.ok检查和catch块,捕获并打印请求错误,方便排查头部或权限问题。
  • 在startTyping函数开头增加数组有效性检查,避免访问不存在的元素。
  • 使用可选链操作符data?.acf?.positions处理可能的嵌套属性缺失问题,同时确保textArray始终是数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:40:32