Skip to content

Commit a9cda58

Browse files
committed
Add study notes for 2025-08-20
1 parent bb5e5b3 commit a9cda58

1 file changed

Lines changed: 89 additions & 0 deletions

File tree

JP3000.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,95 @@ INFJ,珠海,数据科学在读,目前在学习ai agent,ai应用开发,
1515
## Notes
1616

1717
<!-- Content_START -->
18+
# 2025-08-20
19+
20+
### ethers 依赖版本的问题
21+
`TypeError: Cannot read properties of undefined (reading 'Web3Provider')` 依然存在,说明 `ethers.providers` 还是 `undefined`。这通常有以下几种原因:
22+
23+
---
24+
25+
## 1. 依赖版本问题
26+
27+
你可能安装了 ethers v6,但 v6 的导入方式和 v5 不一样。
28+
29+
- **ethers v5** 导入方式(你的代码适用):
30+
```javascript
31+
import { ethers } from 'ethers'
32+
// 使用 ethers.providers.Web3Provider
33+
```
34+
- **ethers v6** 导入方式:
35+
```javascript
36+
import { BrowserProvider } from 'ethers'
37+
// 使用 new BrowserProvider(window.ethereum)
38+
```
39+
40+
如果你用的是 v6,`ethers.providers` 是 undefined。
41+
42+
---
43+
44+
## 2. 解决方法
45+
46+
### 方法一:使用 ethers v5(推荐,兼容你现有代码)
47+
48+
1. 卸载 v6:
49+
```bash
50+
npm uninstall ethers
51+
```
52+
2. 安装 v5:
53+
```bash
54+
npm install ethers@5
55+
```
56+
57+
不用改代码,直接用你现在的写法即可。
58+
59+
---
60+
61+
### 方法二:适配 ethers v6(如果你想用最新版)
62+
63+
1. 保持 `npm install ethers`(v6)
64+
2. 修改 `index.js` 相关代码:
65+
66+
```javascript
67+
import { BrowserProvider, Contract } from 'ethers'
68+
69+
// ...省略...
70+
71+
const addTask = async e => {
72+
e.preventDefault()
73+
let task = {
74+
taskText: input,
75+
isDeleted: false,
76+
}
77+
try {
78+
const { ethereum } = window
79+
if (ethereum) {
80+
const provider = new BrowserProvider(ethereum)
81+
const signer = await provider.getSigner()
82+
const TaskContract = new Contract(
83+
TaskContractAddress,
84+
TaskAbi.abi,
85+
signer
86+
)
87+
await TaskContract.addTask(task.taskText, task.isDeleted)
88+
setTasks([...tasks, task])
89+
console.log("Added task")
90+
} else {
91+
console.log("Ethereum object does not exist")
92+
}
93+
} catch(error) {
94+
console.log(error)
95+
}
96+
}
97+
```
98+
99+
---
100+
101+
## 总结
102+
103+
- 你当前的代码只适用于 ethers v5。
104+
- 如果你用的是 ethers v6,必须改为 `BrowserProvider`
105+
- 推荐直接用 v5,最简单。
106+
18107
# 2025-08-19
19108

20109
### 写具体业务代码

0 commit comments

Comments
 (0)