I need help optimizing a function that returns all divisors
Welcome to Code Review!
When factorising a number, you have the property that; if a number \$ a \$ is factor of \$ n \$, then \$ \frac{n}{a} \$ is also a factor of \$ n \$.
This immediately reduces your loop from \$ 1..n \$ by half to \$ 1..\frac{n}{2} \$.
Now, another optimisation to be done could be memoisation taking into account the property above. If the number \$ \frac{n}{a} \$ is a factor, then all factors of this number would also be factors for your original number \$ n \$.
Next step you can think about is checking only for prime factors, and then using the memoisation of factors from above.
There are several other factorisation algorithms to efficiently calculate. Take a look at some of such algorithms discussed in this article. (https://cp-algorithms.com/algebra/factorization.html)