I know that for conservative forces $\vec{F}=-\nabla{U}$. Let's consider the case of gravitational potential energy, I know that $U=mgy$. Just to check: $\vec{F}=-\nabla{U}=(0,-mg)$: perfect! Now, let's suppose that the body is only allowed to move on the line $y=x$. The potential energy is as before $U=mgy$, but now I could also write it as $U=mgx$.
Then I want the force, let's use the second equivalent expression: $\vec{F}=-\nabla{U}=(-mg,0)$: definitely not! What happened?
I conclude that I must be careful when deriving potential energy. How?
Other similar problems: I force the body to move along a specific constraint and I manage to express the potential as function of say z. Am I allowed to conclude that $F_x=0$ because derivative of a function that not depends on x is zero?
What is the point behind these problems?