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

discord.py运行报错TypeError: Lock对象无法在await表达式中使用求助

问题根因

报错是两个原因共同导致的:

  • 写法不符合标准异步锁的使用规范:Python标准库asyncio.Lock的异步上下文管理器正确用法是async with,而非你代码里的with await
  • 锁类型不匹配:如果你的self._play_lock是用threading.Lock()初始化的同步线程锁,本身不支持await调用,也不适合在异步协程场景使用,会阻塞整个事件循环。

修复步骤

  1. 先修改锁的初始化逻辑,改用异步锁:
import asyncio

# 初始化_play_lock的位置替换为以下代码
self._play_lock = asyncio.Lock()
  1. 修改_play方法中锁的调用写法:
    把原代码中的
with await self._play_lock:

替换为

async with self._play_lock:

修改后的完整_play方法示例:

async def _play(self, _continue=False):
    if self.is_paused and self._current_player:
        return self.resume()

    if self.is_dead:
        return

    async with self._play_lock:
        if self.is_stopped or _continue:
            try:
                entry = await self.playlist.get_next_entry()
            except:
                log.warning("Failed to get entry, retrying", exc_info=True)
                self.loop.call_later(0.1, self.play)
                return

补充说明

如果之前代码可以正常运行,大概率是你之前依赖的第三方组件封装了兼容with await写法的自定义锁,组件版本更新后移除了该兼容逻辑,就触发了标准报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:09:03