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

Livewire 3.0组件重定向失效问题求助

Livewire 3升级后重定向失效且报ReferenceError: attr is not defined的解决办法

问题场景

升级Livewire到3.0版本后,表单内绑定wire:click="cancel"的取消按钮点击后,后台cancel函数可正常执行(已通过dd()验证),返回to_route('produits.index')进行重定向,但页面仅显示进度条消失,目标页面已在开发者工具中加载却不渲染,同时控制台抛出以下错误:

livewire.esm.js:6759 Uncaught (in promise) ReferenceError: attr is not defined
    at cloneScriptTag (livewire.esm.js:6759:12)
    at livewire.esm.js:6724:23
    at NodeList.forEach (<anonymous>)
    at prepNewScriptTagsToRun (livewire.esm.js:6721:42)
    at swapCurrentPageWithNewHtml (livewire.esm.js:6699:7)
    at livewire.esm.js:6813:13
    at preventAlpineFromPickingUpDomChanges (livewire.esm.js:6852:7)
    at livewire.esm.js:6811:11
    at livewire.esm.js:6775:9

解决方案

1. 重新发布Livewire资产并清理缓存

报错源于Livewire的前端核心文件,大概率是资产未正确更新或缓存残留:

  • 执行命令重新发布Livewire前端资产:
    php artisan livewire:publish --assets
    
  • 清理前端构建缓存(根据你的构建工具选择):
    • Vite:npm run build
    • Laravel Mix:npm run prod
  • 强制刷新浏览器缓存(Ctrl+Shift+R),避免加载旧的JS文件。

2. 排查页面中的脚本冲突

错误出现在cloneScriptTag函数,说明Livewire处理页面脚本时遇到了异常,需排查:

  • 检查页面内的自定义脚本标签,是否存在未闭合、语法错误或使用了未定义的attr变量的内联脚本;
  • 临时移除第三方脚本(如jQuery插件、统计脚本等),测试重定向是否恢复正常,逐步定位冲突脚本。

3. 更换重定向实现方式(临时兼容方案)

如果上述方法未生效,可以绕过Livewire的默认重定向逻辑:

方案A:改用redirect()助手函数

public function cancel()
{
    return redirect()->route('produits.index');
}

方案B:通过事件触发前端跳转

组件中分发重定向事件:

public function cancel()
{
    $this->dispatch('triggerRedirect', url: route('produits.index'));
}

页面中添加Alpine监听事件:

<script>
document.addEventListener('livewire:initialized', () => {
    Livewire.on('triggerRedirect', (data) => {
        window.location.href = data.url;
    });
});
</script>

4. 确认版本兼容性

Livewire 3要求Laravel版本≥10.0,若你的Laravel版本过低,会引发兼容性问题,需升级Laravel到符合要求的版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:48:18