The formula for elastic potential energy(for a spring) has been derived by assuming the following things:
1.Work done by a deforming force on a spring from a relaxed state (state where spring is not deformed) to another point would be equal to the elastic potential energy gained by the spring from the relaxed state to that point.
Using this assumption we derived elastic potential energy as: U = $ 1/2$ Kx$^2$
Now let us say that we apply a constant deforming force on a block connected to the spring, now there will be a varying spring force being acted on the block to counter the constant deforming force. Once this deforming force gets greater then the constant deforming force then the deformation of the spring would stop and then the spring will gradually regain its shape.
Now generally it is assumed that the work done by the deforming force from the moment it starts to act to the moment that the deformation of the spring stops is equal to the elastic potential energy gained by the spring.
that is, Initial kinetic energy of spring = final elastic potential energy of spring
But unless the restoring spring force gets larger in magnitude then the constant deforming force the kinetic energy of the spring would keep on increasing and also due to deformation some elastic potential energy will be increasing. Let a point 'A' describe this situation
It is said that the total mechanical energy is conserved in such a system, but in such a situation mechanical energy is not being conserved.
because it is assumed that the kinetic energy when a constant deforming force is just applied is equal to the final elastic potential energy therefore energy is conserved in these two situations but when we compare the total mechanical energy in either of these two situations with the situation at point A then the total energy is not constant(or conserved).
Therefore how can we say that mechanical energy is conserved in such a system? and if it isn't conserved then how we define elastic potential energy to be = $ 1/2$ Kx$^2$